private async Task<BitmapImage> RenderTargetBitmapToBitmapImage(RenderTargetBitmap renderTargetBitmap) { var byteArray = (await renderTargetBitmap.GetPixelsAsync()).ToArray(); var bitmapImage = new BitmapImage(); using (var stream = new InMemoryRandomAccessStream()) { await stream.WriteAsync(byteArray.AsBuffer()); stream.Seek(0); bitmapImage.SetSource(stream); } return bitmapImage; }
另一个
private async Task<BitmapImage> RenderTargetBitmapToBitmapImage(RenderTargetBitmap renderTargetBitmap) { var buffer = await renderTargetBitmap.GetPixelsAsync(); using (var stream = new InMemoryRandomAccessStream()) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, buffer.ToArray() ); await encoder.FlushAsync(); var bitmapImage = new BitmapImage(); bitmapImage.SetSource(stream); return bitmapImage; } }
最终使用 将RenderTargetBitmap (封面缓存图片)对象 转换为 文件二进制 的形式 然后以字符串形式保存在本地json文件中存储
private async Task<byte[]> RenderTargetBitmapToFilebytes(RenderTargetBitmap renderTargetBitmap) { var buffer = await renderTargetBitmap.GetPixelsAsync(); using (var stream = new InMemoryRandomAccessStream()) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)renderTargetBitmap.PixelWidth, (uint)renderTargetBitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, buffer.ToArray() ); await encoder.FlushAsync(); // using (Stream streamExtension = WindowsRuntimeStreamExtensions.AsStreamForRead(stream.GetInputStreamAt(0))) { using (MemoryStream ms = new MemoryStream()) { await streamExtension.CopyToAsync(ms); byte[] fileBytes = ms.ToArray(); return fileBytes; } } } }