本文整理汇总了C#中Windows.Storage.Streams.InMemoryRandomAccessStream.ReadAsync方法的典型用法代码示例。如果您正苦于以下问题:C# InMemoryRandomAccessStream.ReadAsync方法的具体用法?C# InMemoryRandomAccessStream.ReadAsync怎么用?C# InMemoryRandomAccessStream.ReadAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.Storage.Streams.InMemoryRandomAccessStream
的用法示例。
在下文中一共展示了InMemoryRandomAccessStream.ReadAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SaveAsPngIntoBufferAsync
public static async Task<IBuffer> SaveAsPngIntoBufferAsync(this Canvas canvas, double _scaleFactor, int dpiForImage = 200)
{
//string currentresolution = Window.Current.Bounds.Width * scaleFactor + "*" + Window.Current.Bounds.Height * scaleFactor;
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(canvas);
var pixels = await renderTargetBitmap.GetPixelsAsync();
using (IRandomAccessStream stream = new InMemoryRandomAccessStream())
{
var encoder = await
BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
byte[] bytes = pixels.ToArray();
await CoreWindow.GetForCurrentThread().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)(canvas.ActualWidth * _scaleFactor), (uint)(canvas.ActualHeight * _scaleFactor),
dpiForImage, dpiForImage, bytes);
});
await encoder.FlushAsync();
stream.Seek(0);
var buffer = WindowsRuntimeBuffer.Create((int)stream.Size);
await stream.ReadAsync(buffer, (uint)stream.Size, InputStreamOptions.None);
return buffer;
}
}
示例2: GetBijinPicture
private async void GetBijinPicture()
{
var date = DateTime.Now;
var url = "http://www.bijint.com/jp/tokei_images/" + date.ToString("HHmm") + ".jpg";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Referrer = new Uri("http://www.bijint.com/jp/");
using (var strm = await client.GetStreamAsync(new Uri(url)))
{
// BitmapImageインスタンスへはStream型をそのまま読み込ませることができないため、
// InMemoryRandomAccessStreamへソースストリームをコピーする
InMemoryRandomAccessStream ims = new InMemoryRandomAccessStream();
var output = ims.GetOutputStreamAt(0);
await RandomAccessStream.CopyAsync(strm.AsInputStream(), output);
// BitmapImageへソースを設定し、Imageコントロールで表示させる
var bitmap = new BitmapImage();
bitmap.SetSource(ims);
image.Source = bitmap;
// Save用にbyte配列に保存
ims.Seek(0);
imageBuffer = new byte[ims.Size];
IBuffer ibuffer = imageBuffer.AsBuffer();
await ims.ReadAsync(ibuffer, (uint)ims.Size, InputStreamOptions.None);
}
}
示例3: ToQrDataUri
public async static Task<Uri> ToQrDataUri(this ISdp sdp, int width, int height)
{
var qrCodeWriter = new QRCodeWriter();
var bitMatrix = qrCodeWriter.encode(sdp.ToString(), ZXing.BarcodeFormat.QR_CODE, width, height);
using (var canvasRenderTarget = new CanvasRenderTarget(CanvasDevice.GetSharedDevice(), 500, 500, 96))
{
using (var drawingSession = canvasRenderTarget.CreateDrawingSession())
{
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
drawingSession.DrawRectangle(x, y, 1, 1, bitMatrix.get(x, y) ? Color.FromArgb(0, 0, 0, 0) : Color.FromArgb(255, 255, 255, 255));
}
}
}
using (var inMemoryRandomAccessStream = new InMemoryRandomAccessStream())
{
await canvasRenderTarget.SaveAsync(inMemoryRandomAccessStream, CanvasBitmapFileFormat.Png);
inMemoryRandomAccessStream.Seek(0);
var buffer = new byte[inMemoryRandomAccessStream.Size];
await inMemoryRandomAccessStream.ReadAsync(buffer.AsBuffer(), (uint)inMemoryRandomAccessStream.Size, InputStreamOptions.None);
return new Uri($"data:image/png;base64,{Convert.ToBase64String(buffer)}");
}
}
}
示例4: EncodeToBytes
private async Task<byte[]> EncodeToBytes(VideoFrame frame)
{
byte[] array;
using (var stream = new InMemoryRandomAccessStream())
{
var encoder = await CreateBitmapEncoder(stream);
encoder.SetSoftwareBitmap(frame.SoftwareBitmap);
await encoder.FlushAsync();
array = new byte[stream.Size];
await stream.ReadAsync(array.AsBuffer(), (uint) stream.Size, InputStreamOptions.None);
}
return array;
}
示例5: ViewFinder_OnTapped
private async void ViewFinder_OnTapped()
{
ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg();
var stream = new InMemoryRandomAccessStream();
await captureManager.CapturePhotoToStreamAsync(imageProperties, stream);
_bitmap = new WriteableBitmap(300, 300);
stream.Seek(0);
await _bitmap.SetSourceAsync(stream);
stream.Seek(0);
var buffer = new global::Windows.Storage.Streams.Buffer((uint)stream.Size);
stream.ReadAsync(buffer, (uint)stream.Size, InputStreamOptions.None);
await captureManager.StopPreviewAsync();
}
示例6: ToBase64StringAsync
public static async Task<string> ToBase64StringAsync(this WriteableBitmap writeableBitmap)
{
if (writeableBitmap == null)
{
return null;
}
using (var stream = new InMemoryRandomAccessStream())
{
await writeableBitmap.ToStreamAsJpeg(stream);
var bytes = new byte[stream.Size];
await stream.ReadAsync(bytes.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);
return Convert.ToBase64String(bytes, 0, bytes.Length);
}
}
示例7: ResizeAsync
/// <summary>
/// Resizes the image presented by the <paramref name="imageData"/> to a <paramref name="newSize"/>.
/// </summary>
/// <param name="imageData">
/// The binary data of the image to resize.
/// </param>
/// <param name="newSize">
/// The size to which to resize the image.
/// </param>
/// <param name="keepAspectRatio">
/// A flag indicating whether to save original aspect ratio.
/// </param>
/// <returns>
/// The structure which contains binary data of resized image and the actial size of resized image depending on <paramref name="keepAspectRatio"/> value.
/// </returns>
public static async Task<ImageInfo> ResizeAsync(this byte[] imageData, Size newSize, bool keepAspectRatio)
{
var result = new ImageInfo();
var decoder = await BitmapDecoder.CreateAsync(await imageData.AsRandomAccessStreamAsync());
var percentWidth = (double)newSize.Width / (double)decoder.PixelWidth;
var percentHeight = (double)newSize.Height / (double)decoder.PixelHeight;
if (keepAspectRatio)
{
result.Size = percentWidth < percentHeight
? new Size(newSize.Width, (int)(decoder.PixelHeight * percentWidth))
: new Size((int)(decoder.PixelWidth * percentHeight), newSize.Height);
}
else
{
result.Size = newSize;
}
var transform = new BitmapTransform { ScaledWidth = (uint)result.Size.Width, ScaledHeight = (uint)result.Size.Height };
var pixelData = await decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);
using (var destinationStream = new InMemoryRandomAccessStream())
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destinationStream);
encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, (uint)result.Size.Width, (uint)result.Size.Height, 96, 96, pixelData.DetachPixelData());
await encoder.FlushAsync();
var data = new byte[destinationStream.Size];
destinationStream.Seek(0);
await destinationStream.ReadAsync(data.AsBuffer(), (uint)destinationStream.Size, InputStreamOptions.None);
result.Data = data;
}
return result;
}
示例8: LoadImageFromHttpResponse
private async Task<bool> LoadImageFromHttpResponse(HttpResponseMessage response, Tile tile, BitmapSource image, string cacheKey)
{
using (var stream = new InMemoryRandomAccessStream())
{
using (var content = response.Content)
{
await content.WriteToStreamAsync(stream);
}
await stream.FlushAsync();
stream.Seek(0);
var loaded = await LoadImageFromStream(tile, image, stream);
if (loaded && cacheKey != null)
{
var buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size);
stream.Seek(0);
await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None);
var maxAge = DefaultCacheExpiration;
if (response.Headers.CacheControl.MaxAge.HasValue &&
response.Headers.CacheControl.MaxAge.Value < maxAge)
{
maxAge = response.Headers.CacheControl.MaxAge.Value;
}
await Cache.SetAsync(cacheKey, buffer, DateTime.UtcNow.Add(maxAge));
}
return loaded;
}
}
示例9: ConvertImageBufferToJpegBytes
protected async Task<byte[]> ConvertImageBufferToJpegBytes(IBuffer imageBuffer)
{
using (var stream = imageBuffer.AsStream().AsRandomAccessStream())
{
var decoder = await BitmapDecoder.CreateAsync(stream);
var pixels = await decoder.GetPixelDataAsync();
using (var output = new InMemoryRandomAccessStream())
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, output);
await CoreWindow.GetForCurrentThread().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
encoder.SetPixelData(decoder.BitmapPixelFormat, BitmapAlphaMode.Ignore,
decoder.OrientedPixelWidth, decoder.OrientedPixelHeight, decoder.DpiX, decoder.DpiY, pixels.DetachPixelData());
});
await encoder.FlushAsync();
var buffer = WindowsRuntimeBuffer.Create((int)output.Size);
output.Seek(0);
await output.ReadAsync(buffer, (uint)output.Size, InputStreamOptions.None);
return buffer.ToArray();
}
}
}
示例10: ImageToScaledPixels
private async static Task<byte[]> ImageToScaledPixels(BitmapDecoder decoder, uint newWidth)
{
using (var encoderStream = new InMemoryRandomAccessStream())
{
var encoder = await BitmapEncoder.CreateForTranscodingAsync(encoderStream, decoder);
var scaleFactor = decoder.PixelWidth / (double)newWidth;
uint newHeight = (uint)(decoder.PixelHeight / scaleFactor);
encoder.BitmapTransform.ScaledWidth = newWidth;
encoder.BitmapTransform.ScaledHeight = newHeight;
await encoder.FlushAsync();
byte[] pixels = new byte[encoderStream.Size];
await encoderStream.ReadAsync(pixels.AsBuffer(), (uint)pixels.Length, InputStreamOptions.None);
return pixels;
}
}
示例11: GetImageAsByteAsync
private async Task<byte[]> GetImageAsByteAsync(Guid format, int quality, int desiredWidth, int desiredHeight)
{
if (internalImage == null || internalImage.Source == null)
return null;
var bitmap = internalImage.Source as WriteableBitmap;
if (bitmap == null)
return null;
byte[] pixels = null;
uint pixelsWidth = (uint)bitmap.PixelWidth;
uint pixelsHeight = (uint)bitmap.PixelHeight;
if (desiredWidth != 0 || desiredHeight != 0)
{
double widthRatio = (double)desiredWidth / (double)bitmap.PixelWidth;
double heightRatio = (double)desiredHeight / (double)bitmap.PixelHeight;
double scaleRatio = Math.Min(widthRatio, heightRatio);
if (desiredWidth == 0)
scaleRatio = heightRatio;
if (desiredHeight == 0)
scaleRatio = widthRatio;
uint aspectWidth = (uint)((double)bitmap.PixelWidth * scaleRatio);
uint aspectHeight = (uint)((double)bitmap.PixelHeight * scaleRatio);
using (var tempStream = new InMemoryRandomAccessStream())
{
byte[] tempPixels = await GetBytesFromBitmapAsync(bitmap);
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, tempStream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied,
pixelsWidth, pixelsHeight, 96, 96, tempPixels);
await encoder.FlushAsync();
tempStream.Seek(0);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(tempStream);
BitmapTransform transform = new BitmapTransform()
{
ScaledWidth = aspectWidth,
ScaledHeight = aspectHeight,
InterpolationMode = BitmapInterpolationMode.Linear
};
PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
transform,
ExifOrientationMode.RespectExifOrientation,
ColorManagementMode.DoNotColorManage);
pixels = pixelData.DetachPixelData();
pixelsWidth = aspectWidth;
pixelsHeight = aspectHeight;
}
}
else
{
pixels = await GetBytesFromBitmapAsync(bitmap);
}
using (var stream = new InMemoryRandomAccessStream())
{
var encoder = await BitmapEncoder.CreateAsync(format, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied,
pixelsWidth, pixelsHeight, 96, 96, pixels);
await encoder.FlushAsync();
stream.Seek(0);
var bytes = new byte[stream.Size];
await stream.ReadAsync(bytes.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);
return bytes;
}
}
示例12: TakePhotoAsync
/// <summary>
/// Takes a photo to a StorageFile and adds rotation metadata to it
/// </summary>
/// <returns></returns>
private async Task TakePhotoAsync()
{
// While taking a photo, keep the video button enabled only if the camera supports simultaneosly taking pictures and recording video
VideoButton.IsEnabled = _mediaCapture.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported;
// Make the button invisible if it's disabled, so it's obvious it cannot be interacted with
VideoButton.Opacity = VideoButton.IsEnabled ? 1 : 0;
var stream = new InMemoryRandomAccessStream();
try
{
Debug.WriteLine("Taking photo...");
await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
Debug.WriteLine("Photo taken!");
byte[] bytes = new byte[stream.Size];
stream.Seek(0);
var buffer = await stream.ReadAsync(bytes.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);
bytes = buffer.ToArray();
var photoOrientation = ConvertOrientationToPhotoOrientation(GetCameraOrientation());
await ReencodeAndSavePhotoAsync(stream, photoOrientation);
}
catch (Exception ex)
{
Debug.WriteLine("Exception when taking a photo: {0}", ex.ToString());
}
// Done taking a photo, so re-enable the button
VideoButton.IsEnabled = true;
VideoButton.Opacity = 1;
}
示例13: SendPhotoAsync
private async Task SendPhotoAsync()
{
nowTime = DateTime.Now;
if (nowTime.Subtract(preTime).TotalSeconds < 10) return;
if (_isSendingPhoto) return;
_isSendingPhoto = true;
preTime = DateTime.Now;
InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
try
{
Debug.WriteLine("Taking photo...");
await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
Debug.WriteLine("Photo taken!");
byte[] bytes = new byte[stream.Size];
stream.Seek(0);
var buffer = await stream.ReadAsync(bytes.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);
bytes = buffer.ToArray();
Debug.WriteLine("bytes ok!");
HttpWebResponse response = null;
HttpWebRequest request = null;
Stream outstream = null;
StreamReader sr = null;
request = WebRequest.Create(uploadAddress) as HttpWebRequest;
request.ContentType = "application/octet-stream";
request.Method = "POST";
outstream = await request.GetRequestStreamAsync();
await outstream.WriteAsync(bytes, 0, bytes.Length);
////发送请求并获取相应回应数据
response = await request.GetResponseAsync() as HttpWebResponse;
Stream instream = response.GetResponseStream();
Encoding encoding = Encoding.UTF8;
sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
Debug.WriteLine("result :{0} ", content);
JsonArray jArray = JsonArray.Parse(content);
if (jArray != null & jArray.Count >= 1)
{
String stringa = jArray.GetStringAt(0);
if (!stringa.Equals("Invalid"))
{
string playContent = "Welcome";// "欢迎";
int totalNum = jArray.Count; int strangerNum = 0;
for (uint i = 0; i < totalNum; i++)
{
string tempString = jArray.GetStringAt(i);
if (tempString.Equals("Stranger")) strangerNum++;
else playContent += " "+tempString;
}
if (totalNum == strangerNum)
playContent += " " + strangerNum + " friends to my home";// "位朋友莅临寒舍";
else if (strangerNum == 0) playContent += " to my home";// "莅临寒舍";
else playContent += " and other " + strangerNum + " friends to my home"; // "以及其他"+strangerNum+ "位朋友莅临寒舍";
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { this.infoshowText.Text = playContent; PlayTTS(playContent);});
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Exception when taking a photo: {0}", ex.ToString());
}
_isSendingPhoto = false;
}
示例14: SendPhotoAsync
private async Task SendPhotoAsync()
{
nowTime = DateTime.Now;
if (nowTime.Subtract(preTime).TotalSeconds < 10) return;
if (_isSendingPhoto) return;
_isSendingPhoto = true;
// While taking a photo, keep the video button enabled only if the camera supports simultaneosly taking pictures and recording video
//VideoButton.IsEnabled = _mediaCapture.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported;
preTime = DateTime.Now;
// Make the button invisible if it's disabled, so it's obvious it cannot be interacted with
//VideoButton.Opacity = VideoButton.IsEnabled ? 1 : 0;
//InMemoryRandomAccessStream MemoryStream
InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
try
{
Debug.WriteLine("Taking photo...");
await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
Debug.WriteLine("Photo taken!");
byte[] bytes = new byte[stream.Size];
stream.Seek(0);
var buffer = await stream.ReadAsync(bytes.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);
bytes = buffer.ToArray();
Debug.WriteLine("bytes ok!");
//string teststring = "[\"Stranger\",\"Stranger\"]";
//JsonArray jArray = JsonArray.Parse(teststring);
//String stringa = jArray.GetStringAt(0);
//await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { this.infoshowText.Text = stringa; });
//_isSendingPhoto = false;
//return ;
//string content = "欢迎王总莅临寒舍!";
//await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { this.infoshowText.Text = content; });
//await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { PlayTTS(content); });
//_isSendingPhoto = false;
//return ;
HttpWebResponse response = null;
HttpWebRequest request = null;
Stream outstream = null;
StreamReader sr = null;
string requestUri = "http://facedetectionoffice.azurewebsites.net/api/FaceDetection/FaceUpload?DeviceId=3d16334ca04a412388bae34d0dbf300f";
request = WebRequest.Create(requestUri) as HttpWebRequest;
request.ContentType = "application/octet-stream";
request.Method = "POST";
outstream = await request.GetRequestStreamAsync();
await outstream.WriteAsync(bytes, 0, bytes.Length);
////发送请求并获取相应回应数据
response = await request.GetResponseAsync() as HttpWebResponse;
Stream instream = response.GetResponseStream();
Encoding encoding = Encoding.UTF8;
sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
Debug.WriteLine("result :{0} ", content);
JsonArray jArray = JsonArray.Parse(content);
if (jArray != null & jArray.Count >= 1)
{
String stringa = jArray.GetStringAt(0);
if (!stringa.Equals("Invalid"))
{
string playContent = "Welcome";// "欢迎";
int totalNum = jArray.Count; int strangerNum = 0;
for (uint i = 0; i < totalNum; i++)
{
string tempString = jArray.GetStringAt(i);
if (tempString.Equals("Stranger")) strangerNum++;
else playContent += " "+tempString;
}
if (totalNum == strangerNum)
playContent += " " + strangerNum + " friends to my home";// "位朋友莅临寒舍";
else if (strangerNum == 0) playContent += " to my home";// "莅临寒舍";
else playContent += " and other " + strangerNum + " friends to my home"; // "以及其他"+strangerNum+ "位朋友莅临寒舍";
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { this.infoshowText.Text = playContent; PlayTTS(playContent);});
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Exception when taking a photo: {0}", ex.ToString());
}
_isSendingPhoto = false;
// Done taking a photo, so re-enable the button
//VideoButton.IsEnabled = true;
//VideoButton.Opacity = 1;
}
示例15: SaveSoftwareBitmapToBufferAsync
private async Task<byte[]> SaveSoftwareBitmapToBufferAsync(SoftwareBitmap softwareBitmap)
{
byte[] bytes = null;
try
{
IRandomAccessStream stream = new InMemoryRandomAccessStream();
{
// Create an encoder with the desired format
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);
// Set the software bitmap
encoder.SetSoftwareBitmap(softwareBitmap);
// Set additional encoding parameters, if needed
//encoder.BitmapTransform.ScaledWidth = (uint)_width;
//encoder.BitmapTransform.ScaledHeight = (uint)_height;
//encoder.BitmapTransform.Rotation = Windows.Graphics.Imaging.BitmapRotation.Clockwise90Degrees;
//encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
encoder.IsThumbnailGenerated = false;
await encoder.FlushAsync();
bytes = new byte[stream.Size];
// This returns IAsyncOperationWithProgess, so you can add additional progress handling
await stream.ReadAsync(bytes.AsBuffer(), (uint)stream.Size, Windows.Storage.Streams.InputStreamOptions.None);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
return bytes;
}