本文整理汇总了C#中Windows.Storage.Streams.InMemoryRandomAccessStream.AsStreamForWrite方法的典型用法代码示例。如果您正苦于以下问题:C# InMemoryRandomAccessStream.AsStreamForWrite方法的具体用法?C# InMemoryRandomAccessStream.AsStreamForWrite怎么用?C# InMemoryRandomAccessStream.AsStreamForWrite使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.Storage.Streams.InMemoryRandomAccessStream
的用法示例。
在下文中一共展示了InMemoryRandomAccessStream.AsStreamForWrite方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AsRandomAccessStream
public static IRandomAccessStream AsRandomAccessStream( this Stream stream )
{
var randomAccessStream = new InMemoryRandomAccessStream();
var s = randomAccessStream.AsStreamForWrite();
stream.CopyTo(s);
return randomAccessStream;
}
示例2: DrawStrokeOnImageBackground
public byte[] DrawStrokeOnImageBackground(IReadOnlyList<InkStroke> strokes, byte[] backgroundImageBuffer)
{
var stmbuffer = new InMemoryRandomAccessStream();
stmbuffer.AsStreamForWrite().AsOutputStream().WriteAsync(backgroundImageBuffer.AsBuffer()).AsTask().Wait();
CanvasDevice device = CanvasDevice.GetSharedDevice();
var canbit = CanvasBitmap.LoadAsync(device, stmbuffer, 96).AsTask().Result;
CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, canbit.SizeInPixels.Width, canbit.SizeInPixels.Height, 96);
using (var ds = renderTarget.CreateDrawingSession())
{
ds.Clear(Colors.Transparent);
if (backgroundImageBuffer != null)
{
ds.DrawImage(canbit);
}
ds.DrawInk(strokes);
}
var stm = new InMemoryRandomAccessStream();
renderTarget.SaveAsync(stm, CanvasBitmapFileFormat.Png).AsTask().Wait();
var readfrom = stm.GetInputStreamAt(0).AsStreamForRead();
var ms = new MemoryStream();
readfrom.CopyTo(ms);
var outputBuffer = ms.ToArray();
return outputBuffer;
}
示例3: LoadImageAsync
public async Task<BitmapSource> LoadImageAsync(Stream imageStream, Uri uri)
{
if (imageStream == null)
{
return null;
}
var stream = new InMemoryRandomAccessStream();
imageStream.CopyTo(stream.AsStreamForWrite());
stream.Seek(0);
BitmapImage bitmap = new BitmapImage();
await bitmap.SetSourceAsync(stream);
// convert to a writable bitmap so we can get the PixelBuffer back out later...
// in case we need to edit and/or re-encode the image.
WriteableBitmap bmp = new WriteableBitmap(bitmap.PixelHeight, bitmap.PixelWidth);
stream.Seek(0);
bmp.SetSource(stream);
List<Byte> allBytes = new List<byte>();
byte[] buffer = new byte[4000];
int bytesRead = 0;
while ((bytesRead = await imageStream.ReadAsync(buffer, 0, 4000)) > 0)
{
allBytes.AddRange(buffer.Take(bytesRead));
}
DataContainerHelper.Instance.WriteableBitmapToStorageFile(bmp, uri);
return bmp;
}
示例4: Button_Click
private async void Button_Click(object sender, RoutedEventArgs e)
{
var openPicker = new FileOpenPicker
{
ViewMode = PickerViewMode.Thumbnail,
SuggestedStartLocation = PickerLocationId.PicturesLibrary
};
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
var file = await openPicker.PickSingleFileAsync();
if (file == null) return;
using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
// Display input image
var imageIn = new BitmapImage();
await imageIn.SetSourceAsync(fileStream);
InputImage.Source = imageIn;
// Rewind
fileStream.Seek(0);
// Decode
var jpegIn = new JpegDecoder(fileStream.AsStreamForRead()).Decode();
if (!ImageResizer.ResizeNeeded(jpegIn.Image, 320))
{
OutputImage.Source = null;
OutputText.Text = "No resize necessary.";
return;
}
// Resize
var jpegOut = new DecodedJpeg(
new ImageResizer(jpegIn.Image)
.ResizeToScale(320, ResamplingFilters.NearestNeighbor),
jpegIn.MetaHeaders); // Retain EXIF details
// Encode
using (var outStream = new InMemoryRandomAccessStream())
{
new JpegEncoder(jpegOut, 90, outStream.AsStreamForWrite()).Encode();
// Display
outStream.Seek(0);
var image = new BitmapImage();
await image.SetSourceAsync(outStream);
OutputImage.Source = image;
}
}
}
示例5: Create
///<summary>
/// Creates a file parameter from an array of bytes.
///</summary>
///<param name="name">The parameter name to use in the request.</param>
///<param name="data">The data to use as the file's contents.</param>
///<param name="filename">The filename to use in the request.</param>
///<param name="contentType">The content type to use in the request.</param>
///<returns>The <see cref="FileParameter"/></returns>
public static FileParameter Create(string name, [ReadOnlyArray]byte[] data, string filename, string contentType)
{
var length = (long)data.Length;
var stream = new InMemoryRandomAccessStream();
stream.AsStreamForWrite().Write(data,0,data.Length);
return new FileParameter
{
Content = data,
FileName = filename,
ContentType = contentType,
ContentLength = length,
Name = name
};
}
示例6: Convert
public object Convert(object value, Type targetType, object parameter, string language)
{
// Get bytes and create new bitmap image
byte[] bytes = value as byte[];
BitmapImage image = new BitmapImage();
// Write bytes to stream
InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
stream.AsStreamForWrite().Write(bytes, 0, bytes.Length);
stream.Seek(0);
// Set stream as image source
image.SetSource(stream);
ImageSource source = image;
return image;
}
示例7: Convert
public object Convert(object value, Type targetType, object parameter, string culture)
{
try
{
Message message = value as Message;
byte[] imageBytes = (message.Attachments[0] as FileAttachment).ContentBytes;
BitmapImage image = new BitmapImage();
image.DecodePixelWidth = 300;
InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();
ms.AsStreamForWrite(imageBytes.Length).Write(imageBytes, 0, imageBytes.Length);
ms.Seek(0);
image.SetSource(ms);
return image;
}
catch (Exception ex)
{
throw ex;
}
}
示例8: GetImage
protected async Task<WriteableBitmap> GetImage(string url)
{
try
{
IBuffer buffer = await BaseService.SendGetRequestAsBytes(url);
if (buffer != null)
{
BitmapImage bi = new BitmapImage();
WriteableBitmap wb = null; Stream stream2Write;
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
stream2Write = stream.AsStreamForWrite();
await stream2Write.WriteAsync(buffer.ToArray(), 0, (int)buffer.Length);
await stream2Write.FlushAsync();
stream.Seek(0);
await bi.SetSourceAsync(stream);
wb = new WriteableBitmap(bi.PixelWidth, bi.PixelHeight);
stream.Seek(0);
await wb.SetSourceAsync(stream);
return wb;
}
}
else
{
return null;
}
}
catch
{
return null;
}
}
示例9: Load
public async Task<IBitmap> Load(Stream sourceStream, float? desiredWidth, float? desiredHeight)
{
using (var rwStream = new InMemoryRandomAccessStream()) {
await sourceStream.CopyToAsync(rwStream.AsStreamForWrite());
var decoder = await BitmapDecoder.CreateAsync(rwStream);
var transform = new BitmapTransform();
if (desiredWidth != null) {
transform.ScaledWidth = (uint)desiredWidth;
transform.ScaledHeight = (uint)desiredHeight;
}
var pixelData = await decoder.GetPixelDataAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb);
var pixels = pixelData.DetachPixelData();
WriteableBitmap bmp = new WriteableBitmap((int)decoder.OrientedPixelWidth, (int)decoder.OrientedPixelHeight);
using (var bmpStream = bmp.PixelBuffer.AsStream()) {
bmpStream.Seek(0, SeekOrigin.Begin);
bmpStream.Write(pixels, 0, (int)bmpStream.Length);
return (IBitmap) new WriteableBitmapImageBitmap(bmp);
}
}
}
示例10: GetImageResponse
/// <summary>
/// 向服务器发送请求 获取图片
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
async public Task<WriteableBitmap> GetImageResponse(string url)
{
try
{
IBuffer buffer = await BaseService.SendGetRequestAsBytesAsync(url);
if (buffer != null)
{
BitmapImage bitmapImage = new BitmapImage();
using (var memoryStream = new InMemoryRandomAccessStream())
{
Stream streamWriter = memoryStream.AsStreamForWrite();
await streamWriter.WriteAsync(buffer.ToArray(), 0, (int)buffer.Length);
await streamWriter.FlushAsync();
memoryStream.Seek(0);
await bitmapImage.SetSourceAsync(memoryStream);
WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
memoryStream.Seek(0);
await writeableBitmap.SetSourceAsync(memoryStream);
return writeableBitmap;
}
}
return null;
}
catch (Exception)
{
return null;
}
}
示例11: ServiceRequest
/// <summary>
/// Used to service the given request. Once the image has been responded to the
/// function will continue with requests until the queue is empty
/// </summary>
/// <param name="startingRequestedContext">The request to start with</param>
/// <returns></returns>
private async Task ServiceRequest(ImageManagerRequestInternal startingRequestedContext)
{
ImageManagerRequestInternal currentRequest = startingRequestedContext;
while (currentRequest != null)
{
// Service the request in a try catch
try
{
string fileName = MakeFileNameFromUrl(currentRequest.Context.Url);
// First check if we have the file
if (m_baconMan.CacheMan.HasFileCached(fileName))
{
// If we have it cached pull it from there
}
else
{
// If not we have to get the image
IBuffer imgBuffer = await m_baconMan.NetworkMan.MakeRawGetRequest(currentRequest.Context.Url);
// Turn the stream into an image
InMemoryRandomAccessStream imageStream = new InMemoryRandomAccessStream();
Stream readStream = imgBuffer.AsStream();
Stream writeStream = imageStream.AsStreamForWrite();
// Copy the buffer
// #todo perf - THERE HAS TO BE A BTTER WAY TO DO THIS.
readStream.CopyTo(writeStream);
writeStream.Flush();
// Seek to the start.
imageStream.Seek(0);
// Create a response
ImageManagerResponseEventArgs response = new ImageManagerResponseEventArgs()
{
ImageStream = imageStream,
Request = currentRequest.Context,
Success = true
};
// Fire the callback
currentRequest.Context.m_onRequestComplete.Raise(currentRequest.Context, response);
}
}
catch (Exception e)
{
// Report the error
m_baconMan.MessageMan.DebugDia("Error getting image", e);
// Create a response
ImageManagerResponseEventArgs response = new ImageManagerResponseEventArgs()
{
Request = currentRequest.Context,
Success = false
};
// Send the response
currentRequest.Context.m_onRequestComplete.Raise(currentRequest.Context, response);
}
// Once we are done, check to see if there is another we should service.
lock (m_requestList)
{
// Remove the current request.
m_requestList.Remove(currentRequest);
// Kill the current request
currentRequest = null;
// Check if there is another request we should service now.
for (int i = 0; i < MAX_RUNNING_IMAGE_REQUESTS; i++)
{
if (m_requestList.Count > i && !m_requestList[i].isServicing)
{
currentRequest = m_requestList[i];
currentRequest.isServicing = true;
break;
}
}
}
}
}
示例12: SendEmailWithLogsAsync
public static async Task SendEmailWithLogsAsync(string recipient, string appName)
{
EmailRecipient emailRecipient = new EmailRecipient(recipient);
EmailMessage emailMsg = new EmailMessage { Subject = string.Format("Feedback from {0} with logs", appName) };
emailMsg.To.Add(emailRecipient);
//emailMsg.Body = await ReadAllLogsIntoStringAsync(); // LOLLO this only works with a short body...
string body = await ReadAllLogsIntoStringAsync();
using (var ms = new InMemoryRandomAccessStream())
{
using (var s4w = ms.AsStreamForWrite())
{
using (var sw = new StreamWriter(s4w, Encoding.UTF8))
{
await sw.WriteAsync(body);
await sw.FlushAsync();
// LOLLO NOTE the emails are broken with Outlook, they work with the mail app tho
// https://msdn.microsoft.com/en-us/library/windows/apps/xaml/mt269391.aspx
// the following brings up a preview with only the beginning of the body, at least with Outlook.
// it truncates the body if it is too long, like with mailto:
// emailMsg.SetBodyStream(EmailMessageBodyKind.PlainText, RandomAccessStreamReference.CreateFromStream(ms0));
// the following instead does not work at all, at least with Outlook: no attachments are attached; the email app works fine
emailMsg.Body = "I have attached the logs";
ms.Seek(0);
var att = new EmailAttachment("Logs.txt", RandomAccessStreamReference.CreateFromStream(ms)); //, "text/plain");
emailMsg.Attachments.Add(att);
//await s4w.FlushAsync();
//await ms.FlushAsync();
emailMsg.Attachments[0].EstimatedDownloadSizeInBytes = ms.Size;
await EmailManager.ShowComposeNewEmailAsync(emailMsg); //.AsTask().ConfigureAwait(false);
}
}
}
}
示例13: SetAsLockScreen_Click
private async void SetAsLockScreen_Click(object sender, RoutedEventArgs e)
{
var item = flipView.SelectedItem as NatGeoImage;
// It's recommended to use both SetBitmap and SetStorageItems for sharing a single image
// since the target app may only support one or the other.
var client = new HttpClient();
var r = new HttpRequestMessage(
HttpMethod.Get, item.DownloadUrl ?? item.ImageUrl);
HttpResponseMessage response = await client.SendAsync(r,
HttpCompletionOption.ResponseHeadersRead);
var ims = new InMemoryRandomAccessStream();
var imsWriter = ims.AsStreamForWrite();
await response.Content.CopyToAsync(imsWriter);
await LockScreen.SetImageStreamAsync(ims);
ToashNotification("Lock screen set.");
}
示例14: LoadImage
async private Task LoadImage()
{
if (string.IsNullOrEmpty(ImageUrl) || !ImageUrl.ToLower().EndsWith(".gif"))
{
this.ProgressRing.Visibility = Visibility.Collapsed;
this.ErrorIcon.Visibility = Visibility.Visible;
return;
}
try
{
var speeds = new List<TimeSpan>();
using (var webClient = new HttpClient())
{
using (var response = await webClient.GetAsync(ImageUrl))
{
if (!response.IsSuccessStatusCode)
{
this.ProgressRing.Visibility = Visibility.Collapsed;
this.ErrorIcon.Visibility = Visibility.Visible;
return;
}
using (var imageStream = await response.Content.ReadAsStreamAsync())
{
BitmapDecoder imageDecoder;
using (var randomAccessStream = new InMemoryRandomAccessStream())
{
await imageStream.CopyToAsync(randomAccessStream.AsStreamForWrite());
imageDecoder =
await BitmapDecoder.CreateAsync(BitmapDecoder.GifDecoderId, randomAccessStream);
FrameCount = imageDecoder.FrameCount;
// Clear old bitmaps in case the control is being reused
bitmapFrames.Clear();
byte[] lastFrame = null;
var totalWidth = 0;
// Extract each frame and create a WriteableBitmap for each of these (store them in an internal list)
for (uint frameIndex = 0; frameIndex < FrameCount; frameIndex++)
{
var frame = await imageDecoder.GetFrameAsync(frameIndex);
var propertyDictionary =
await
frame.BitmapProperties.GetPropertiesAsync(
new List<string>
{
"/imgdesc/Width",
"/imgdesc/Height",
"/imgdesc/Left",
"/imgdesc/Top",
"/grctlext/Delay"
});
var test =
await
frame.BitmapProperties.GetPropertiesAsync(new List<string> { "/grctlext" });
var test2 =
await
(test["/grctlext"].Value as BitmapPropertiesView).GetPropertiesAsync(
new List<string>());
var list = test2.ToList();
speeds.Add(
TimeSpan.FromMilliseconds(
double.Parse(propertyDictionary["/grctlext/Delay"].Value.ToString()) * 10));
var top = int.Parse(propertyDictionary["/imgdesc/Top"].Value.ToString());
var left = int.Parse(propertyDictionary["/imgdesc/Left"].Value.ToString());
var width = int.Parse(propertyDictionary["/imgdesc/Width"].Value.ToString());
var height = int.Parse(propertyDictionary["/imgdesc/Height"].Value.ToString());
var writeableBitmap = new WriteableBitmap(
(int)imageDecoder.OrientedPixelWidth,
(int)imageDecoder.OrientedPixelHeight);
// Extract the pixel data and fill the WriteableBitmap with them
var bitmapTransform = new BitmapTransform();
var pixelDataProvider =
await
frame.GetPixelDataAsync(
BitmapPixelFormat.Bgra8,
imageDecoder.BitmapAlphaMode,
bitmapTransform,
ExifOrientationMode.IgnoreExifOrientation,
ColorManagementMode.DoNotColorManage);
var pixels = pixelDataProvider.DetachPixelData();
if (lastFrame != null)
{
for (var j = 0; j < height; j++)
{
for (var i = 0; i < width; i++)
{
var offset = (i + (j * width)) * 4;
if (pixels[offset + 3] == 0)
//.........这里部分代码省略.........
示例15: UriImageSaveLocalAsync
/// <summary>
/// 문자열 이미지 uri를 받아서 이미지를 로컬에 저장하고 BitmapImage로 반환한다.
/// </summary>
/// <param name="imageUri"></param>
/// <returns></returns>
public async Task<BitmapImage> UriImageSaveLocalAsync(string imageUri, bool retry = true)
{
if (string.IsNullOrEmpty(imageUri) == true) return null;
//폴더 초기화 될때까지 대기
while (files == null)
{
await TaskEx.Delay(500);
}
//Stream
var iuri = new Uri(imageUri, UriKind.Absolute);
string filename = System.IO.Path.GetFileName(iuri.LocalPath);
//메모리 내용확인
var mbi = GetImage(filename);
if (mbi != null)
{
return mbi;
}
Stream imageStream = null; //기본 스트림
//IRandomAccessStream
InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
//create bitmap
BitmapImage bi = new BitmapImage();
//폴더에 파일 존재 확인
if (files.Any(p => p.Name == filename))
{
var localFile = files.First(p => p.Name == filename);
bi.UriSource = new Uri(Path.Combine(ApplicationData.Current.TemporaryFolder.Path, localFile.Name));
AddImage(filename, bi);
//try
//{
// imageStream = await localFile.OpenStreamForReadAsync();
//}
//catch (Exception)
//{
// //파일 열때 에러가 발생하면, 파일이 존재하지 않기 때문일 수 있는..
// UpdateFolder();
// bi.UriSource = new Uri(imageUri);
// if (imageStream != null) imageStream.Dispose();
// if (ras != null) ras.Dispose();
// return bi;
//}
//await imageStream.CopyToAsync(ras.AsStreamForWrite());
//if (ras.Size > 0)
//{
// ras.Seek(0);
// await bi.SetSourceAsync(ras);
// //메모리에 저장
// AddImage(filename, bi);
//}
//else
//{
// //파일 이상인듯
// await localFile.DeleteAsync();
// UpdateFolder();
// //재귀호출
// if (retry == false)
// {
// if (imageStream != null) imageStream.Dispose();
// if (ras != null) ras.Dispose();
// return await UriImageSaveLocalAsync(imageUri, true);
// }
// else
// {
// bi.UriSource = new Uri(imageUri);
// if (imageStream != null) imageStream.Dispose();
// if (ras != null) ras.Dispose();
// return bi;
// }
//}
}
else
{
using (HttpClient hc = new HttpClient())
{
try
{
imageStream = await hc.GetStreamAsync(imageUri);
}
catch (Exception)
{
//네트워크 상태가 끊어졌을 때
bi.UriSource = new Uri(imageUri);
if (imageStream != null) imageStream.Dispose();
if (ras != null) ras.Dispose();
return bi;
}
//Stream -> IRandomAccessStream
await imageStream.CopyToAsync(ras.AsStreamForWrite());
if (ras.Size > 0)
{
//.........这里部分代码省略.........