本文整理汇总了C#中Windows.Storage.Streams.InMemoryRandomAccessStream类的典型用法代码示例。如果您正苦于以下问题:C# InMemoryRandomAccessStream类的具体用法?C# InMemoryRandomAccessStream怎么用?C# InMemoryRandomAccessStream使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
InMemoryRandomAccessStream类属于Windows.Storage.Streams命名空间,在下文中一共展示了InMemoryRandomAccessStream类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ResizeImage
async Task<WriteableBitmap> ResizeImage(WriteableBitmap baseWriteBitmap, uint width, uint height)
{
Stream stream = baseWriteBitmap.PixelBuffer.AsStream();
byte[] pixels = new byte[(uint)stream.Length];
await stream.ReadAsync(pixels, 0, pixels.Length);
var inMemoryRandomStream = new InMemoryRandomAccessStream();
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, inMemoryRandomStream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)baseWriteBitmap.PixelWidth, (uint)baseWriteBitmap.PixelHeight, 96, 96, pixels);
await encoder.FlushAsync();
var transform = new BitmapTransform
{
ScaledWidth = width,
ScaledHeight = height
};
inMemoryRandomStream.Seek(0);
var decoder = await BitmapDecoder.CreateAsync(inMemoryRandomStream);
var pixelData = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Straight,
transform,
ExifOrientationMode.IgnoreExifOrientation,
ColorManagementMode.DoNotColorManage);
var sourceDecodedPixels = pixelData.DetachPixelData();
var inMemoryRandomStream2 = new InMemoryRandomAccessStream();
var encoder2 = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, inMemoryRandomStream2);
encoder2.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, width, height, 96, 96, sourceDecodedPixels);
await encoder2.FlushAsync();
inMemoryRandomStream2.Seek(0);
var bitmap = new WriteableBitmap((int)width, (int)height);
await bitmap.SetSourceAsync(inMemoryRandomStream2);
return bitmap;
}
示例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: ImageToBytes
private async Task<byte[]> ImageToBytes(IRandomAccessStream sourceStream)
{
byte[] imageArray;
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);
var transform = new BitmapTransform { ScaledWidth = decoder.PixelWidth, ScaledHeight = decoder.PixelHeight };
PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Rgba8,
BitmapAlphaMode.Straight,
transform,
ExifOrientationMode.RespectExifOrientation,
ColorManagementMode.DoNotColorManage);
using (var destinationStream = new InMemoryRandomAccessStream())
{
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream);
encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, decoder.PixelWidth,
decoder.PixelHeight, 96, 96, pixelData.DetachPixelData());
await encoder.FlushAsync();
BitmapDecoder outputDecoder = await BitmapDecoder.CreateAsync(destinationStream);
await destinationStream.FlushAsync();
imageArray = (await outputDecoder.GetPixelDataAsync()).DetachPixelData();
}
return imageArray;
}
示例4: OnDeferredImageRequestedHandler
private async void OnDeferredImageRequestedHandler(DataProviderRequest request)
{
// In this delegate we provide updated Bitmap data using delayed rendering.
if (_imageFile != null)
{
// If the delegate is calling any asynchronous operations it needs to acquire
// the deferral first. This lets the system know that you are performing some
// operations that might take a little longer and that the call to SetData
// could happen after the delegate returns. Once you acquired the deferral object
// you must call Complete on it after your final call to SetData.
DataProviderDeferral deferral = request.GetDeferral();
InMemoryRandomAccessStream inMemoryStream = new InMemoryRandomAccessStream();
// Make sure to always call Complete when finished with the deferral.
try
{
// Decode the image and re-encode it at 50% width and height.
IRandomAccessStream imageStream = await _imageFile.OpenAsync(FileAccessMode.Read);
BitmapDecoder imageDecoder = await BitmapDecoder.CreateAsync(imageStream);
BitmapEncoder imageEncoder = await BitmapEncoder.CreateForTranscodingAsync(inMemoryStream, imageDecoder);
imageEncoder.BitmapTransform.ScaledWidth = (uint)(imageDecoder.OrientedPixelWidth * 0.5);
imageEncoder.BitmapTransform.ScaledHeight = (uint)(imageDecoder.OrientedPixelHeight * 0.5);
await imageEncoder.FlushAsync();
request.SetData(RandomAccessStreamReference.CreateFromStream(inMemoryStream));
}
finally
{
deferral.Complete();
}
}
}
示例5: RenderUIElement
private async Task RenderUIElement(FrameworkElement elm, string fileName, int width, int height) {
await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(1));
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(elm);
var pixels = await renderTargetBitmap.GetPixelsAsync();
var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ms);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
logicalDpi,
logicalDpi,
pixels.ToArray());
await encoder.FlushAsync();
await X.Services.Image.Service.Instance.GenerateResizedImageAsync(width, elm.ActualWidth, elm.ActualHeight, ms, fileName + ".png", Services.Image.Service.location.TileFolder, height);
}
}
示例6: SaveResultToCameraRollAsync
/// <summary>
/// Asynchronously saves the <paramref name="photo" /> given to the camera roll album.
/// </summary>
/// <param name="photo">Photo to save.</param>
/// <returns>Image with thumbnail.</returns>
/// <exception cref="ArgumentNullException"><paramref name="photo"/> is <see langword="null"/>.</exception>
public async Task<IThumbnailedImage> SaveResultToCameraRollAsync(ICapturedPhoto photo)
{
if (photo == null)
{
throw new ArgumentNullException("photo");
}
Tracing.Trace("StorageService: Trying to save picture to the Camera Roll.");
Picture cameraRollPicture;
string name = this.GeneratePhotoName();
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
// Convert image to JPEG format and rotate in accordance with the original photo orientation.
Tracing.Trace("StorageService: Converting photo to JPEG format. Size: {0}x{1}, Rotation: {2}", photo.Width, photo.Height, photo.Rotation);
byte[] pixelData = await photo.DetachPixelDataAsync();
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
encoder.BitmapTransform.Rotation = photo.Rotation;
encoder.BitmapTransform.Flip = photo.Flip;
encoder.IsThumbnailGenerated = true;
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, photo.Width, photo.Height, Constants.DefaultDpiX, Constants.DefaultDpiY, pixelData);
await encoder.FlushAsync();
cameraRollPicture = this.lazyMediaLibrary.Value.SavePictureToCameraRoll(name, stream.AsStream());
}
Tracing.Trace("StorageService: Saved to Camera Roll as {0}", name);
return new MediaLibraryThumbnailedImage(cameraRollPicture);
}
示例7: GetBijinPicture
public async Task<BitmapImage> GetBijinPicture(string Path)
{
var date = DateTime.Now;
var url = "http://www.bijint.com/" + Path + "/tokei_images/" + date.ToString("HHmm") + ".jpg";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Referrer = new Uri("http://www.bijint.com/" + Path);
BitmapImage bitmap;
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コントロールで表示させる
bitmap = new BitmapImage();
bitmap.SetSource(ims);
}
return bitmap;
//var html = await client.GetStringAsync("http://www.bijint.com/kobe/cache/" + date.ToString("HHmm") + ".html");
//this.html.NavigateToString(html);
}
示例8: bookmarkBtn_Click
/// <summary>
/// This is the click handler for the 'Solution' button.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void bookmarkBtn_Click(object sender, RoutedEventArgs e)
{
InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();
await webView8.CapturePreviewToStreamAsync(ms);
//Create a small thumbnail
int longlength = 180, width = 0, height = 0;
double srcwidth = webView8.ActualWidth, srcheight = webView8.ActualHeight;
double factor = srcwidth / srcheight;
if (factor < 1)
{
height = longlength;
width = (int)(longlength * factor);
}
else
{
width = longlength;
height = (int)(longlength / factor);
}
BitmapSource small = await resize(width, height, ms);
BookmarkItem item = new BookmarkItem();
item.Title = webView8.DocumentTitle;
item.PageUrl = webView8.Source;
item.Preview = small;
bookmarks.Add(item);
}
示例9: ReadAsync
/// <summary>
/// Continuously look for a QR code
/// NOTE: this method won't work if recording is enabled ('hey Cortana, start recording' thing).
/// </summary>
public static async Task<string> ReadAsync(CancellationToken token = default(CancellationToken))
{
var mediaCapture = new MediaCapture();
await mediaCapture.InitializeAsync();
await mediaCapture.AddVideoEffectAsync(new MrcVideoEffectDefinition(), MediaStreamType.Photo);
var reader = new BarcodeReader();
reader.Options.TryHarder = false;
while (!token.IsCancellationRequested)
{
var imgFormat = ImageEncodingProperties.CreateJpeg();
using (var ras = new InMemoryRandomAccessStream())
{
await mediaCapture.CapturePhotoToStreamAsync(imgFormat, ras);
var decoder = await BitmapDecoder.CreateAsync(ras);
using (var bmp = await decoder.GetSoftwareBitmapAsync())
{
Result result = await Task.Run(() =>
{
var source = new SoftwareBitmapLuminanceSource(bmp);
return reader.Decode(source);
});
if (!string.IsNullOrEmpty(result?.Text))
return result.Text;
}
}
await Task.Delay(DelayBetweenScans);
}
return null;
}
示例10: 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);
}
}
示例11: RenderToRandomAccessStream
public static async Task<IRandomAccessStream> RenderToRandomAccessStream(this UIElement element) {
var rtb = new RenderTargetBitmap();
await rtb.RenderAsync(element);
IBuffer pixelBuffer = await rtb.GetPixelsAsync();
byte[] pixels = pixelBuffer.ToArray();
// Useful for rendering in the correct DPI
DisplayInformation displayInformation = DisplayInformation.GetForCurrentView();
var stream = new InMemoryRandomAccessStream();
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
(uint)rtb.PixelWidth,
(uint)rtb.PixelHeight,
displayInformation.RawDpiX,
displayInformation.RawDpiY,
pixels);
await encoder.FlushAsync();
stream.Seek(0);
return stream;
}
示例12: ConvertToRandomAccessStream
public static async Task<IRandomAccessStream> ConvertToRandomAccessStream(Stream source)
{
Stream streamToConvert = null;
if (!source.CanRead)
throw new Exception("The source cannot be read.");
if (!source.CanSeek)
{
var memStream = new MemoryStream();
await source.CopyToAsync(memStream);
streamToConvert = memStream;
}
else
{
streamToConvert = source;
}
var reader = new DataReader(streamToConvert.AsInputStream());
streamToConvert.Position = 0;
await reader.LoadAsync((uint) streamToConvert.Length);
var buffer = reader.ReadBuffer((uint) streamToConvert.Length);
var randomAccessStream = new InMemoryRandomAccessStream();
var outputStream = randomAccessStream.GetOutputStreamAt(0);
await outputStream.WriteAsync(buffer);
await outputStream.FlushAsync();
return randomAccessStream;
}
示例13: FromStream
internal static Bitmap FromStream(Stream stream)
{
Bitmap bitmap = null;
Task.Run(async () =>
{
using (var raStream = new InMemoryRandomAccessStream())
{
await stream.CopyToAsync(raStream.AsStream());
var decoder = await BitmapDecoder.CreateAsync(raStream);
var pixelData = await decoder.GetPixelDataAsync();
var width = (int)decoder.OrientedPixelWidth;
var height = (int)decoder.OrientedPixelHeight;
const PixelFormat format = PixelFormat.Format32bppArgb;
var bytes = pixelData.DetachPixelData();
bitmap = new Bitmap(width, height, format);
var data = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, format);
Marshal.Copy(bytes, 0, data.Scan0, bytes.Length);
bitmap.UnlockBits(data);
}
}).Wait();
return bitmap;
}
示例14: BeginReadCCTV
async void BeginReadCCTV()
{
IsBeginRead = true;
ISExit = false;
tblCCTV cctvinfo=null;
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
cctvinfo = this.DataContext as tblCCTV;
});
// client=new HttpClient();
while (!ISExit)
{
try
{
Uri uri = new Uri("http://192.192.161.3/" + cctvinfo.REF_CCTV_ID.Trim() + ".jpg?" + rnd.Next(), UriKind.Absolute);
using (httpClient = new HttpClient())
{
httpClient.Timeout = TimeSpan.FromSeconds(0.5);
var contentBytes = await httpClient.GetByteArrayAsync(uri);
var ims = new InMemoryRandomAccessStream();
var dataWriter = new DataWriter(ims);
dataWriter.WriteBytes(contentBytes);
await dataWriter.StoreAsync();
//ims.seak 0
ims.Seek(0 );
await Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal,()=>
{
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(ims );
this.imgCCTV.Source = bitmap;
imginx = (imginx + 1) % 90000;
this.RunFrameRate.Text = imginx.ToString();
});
}
}
catch (Exception ex)
{
// this.textBlock1.Text = ex.Message;
}
// BitmapImage img = new BitmapImage();
// img.SetSource(stream);
}
}
示例15: RenderToBase64
public async Task<string> RenderToBase64(UIElement element)
{
RenderTargetBitmap rtb = new RenderTargetBitmap();
await rtb.RenderAsync(element);
var pixelBuffer = await rtb.GetPixelsAsync();
var pixels = pixelBuffer.ToArray();
// Useful for rendering in the correct DPI
var displayInformation = DisplayInformation.GetForCurrentView();
var stream = new InMemoryRandomAccessStream();
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
(uint)rtb.PixelWidth,
(uint)rtb.PixelHeight,
displayInformation.RawDpiX,
displayInformation.RawDpiY,
pixels);
await encoder.FlushAsync();
stream.Seek(0);
// read bytes
var bytes = new byte[stream.Size];
await stream.AsStream().ReadAsync(bytes, 0, bytes.Length);
// create base64
return Convert.ToBase64String(bytes);
}