简体   繁体   中英

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

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

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM