0

我目前正在尝试将从 RenderTargetBitmap 获得的 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 元素,用于检查转换是否成功

编辑:这段代码我没有例外,应用程序只是冻结

4

2 回答 2

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);

有时这对我有用,遗憾的是有时它仍然会出错,但我不知道为什么

于 2016-05-12T13:30:37.767 回答
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;
于 2015-06-19T11:19:42.070 回答