个人资料

跳过导航链接首页 > 博客列表 > 博客正文

Convert RenderTargetBitmap To BitmapImage in UWP application

分类:
		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;
					}
				}
			
			}

		}









songshizhao
最初发表2019/12/13 21:52:03 最近更新2019/12/14 0:46:32 2600
为此篇作品打分
10
   评论