我目前正在尝试将我从RenderTargetBitmap转换为Base64String的IBuffer转换为Base64String,反之亦然。我在Silverlight中成功地做了类似的事情,但现在在Windows运行时,有很多库缺失,我不知道现在要尝试什么。
以下是我最新的示例代码,它不会产生任何错误,但是当我尝试运行它时,它会让我的应用程序崩溃。有什么建议吗?
提前致谢
var bitmap = new RenderTargetBitmap();
await bitmap.RenderAsync(drawingPanel);
IBuffer pixel = await bitmap.GetPixelsAsync();
String b64 = CryptographicBuffer.EncodeToBase64String(pixel);
IBuffer backpixel = CryptographicBuffer.DecodeFromBase64String(b64);
WriteableBitmap wb = new WriteableBitmap(bitmap.PixelWidth, bitmap.PixelHeight);
wb.SetSource(backpixel.AsStream().AsRandomAccessStream());
imageBox.Source = wb;
imageBox是一个XAML元素,用于检查转换是否成功
编辑:我对此代码没有例外,应用程序只是冻结答案 0 :(得分:2)
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(MyCanvas);
var bitmap = renderTargetBitmap;
var img = (await bitmap.GetPixelsAsync()).ToArray();
var encoded = new InMemoryRandomAccessStream();
var encoder = await BitmapEncoder.CreateAsync(
BitmapEncoder.PngEncoderId, encoded);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight,
(uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96, 96, img);
await encoder.FlushAsync();
encoded.Seek(0);
var bytes = new byte[encoded.Size];
await encoded.AsStream().ReadAsync(bytes, 0, bytes.Length);
return Convert.ToBase64String(bytes);
有时这对我有用,遗憾的是它有时会出错但我不知道为什么
答案 1 :(得分:0)
使用以下内容,我想我会工作
var bitmap = new RenderTargetBitmap();
await bitmap.RenderAsync(drawingPanel);
IBuffer pixel = await bitmap.GetPixelsAsync();
Stream stream = pixel.AsStream();
BitmapImage bitmapImage = new BitmapImage();
using (IRandomAccessStream raStream = stream.AsRandomAccessStream())
{
bitmapImage.SetSource(raStream);
}
imageBox.Source = bitmapImage;