Windows Phone Runtime: RendertargetBitmap/IBuffer to Base64 and vice versa

417 views Asked by At

Im currently trying to Convert an IBuffer I get from a RenderTargetBitmap to a Base64String and vice versa. I successfully did something like that in Silverlight, but now in Windows Runtime there are so many libraries missing that i dont know what to try now.

Below is my latest sample codes which doesnt make any errors, but it lets crash my App when i try to run it. Any suggestions?

Thanks in advance

        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 is a XAML element to check out if the conversion was successful

EDIT: I get no exceptions with this code, the app just freezes

2

There are 2 answers

1
Rehan Parvez On

Use the below, I think I will work

                    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;
0
Supermaniac On
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);

Sometimes this works for me, sadly it still gives errors sometimes but I don't know why