Close

IRandomAccessStream to WriteableBitmap

Bueno, después de una larga búsqueda en Internet no conseguía solucionar el error en UWP.

Pense que era algo tribial pero no.

Siempre que hacia un «PixelBuffer» para leerlo como stream, fallaba el código y saltaba una excepción de tipo «No se encuentra el componente. (Excepción de HRESULT: 0x88982F50)».

var stream = writeableBitmap.PixelBuffer.AsStream();

Como ya estamos acostumbrados a que Microsoft. nos detalle el error fue «Facil» buscar la solución. XD.

Bueno al final la solución fue inicializar el objeto dos veces.

He aquí las lineas de código.

 public WriteableBitmap StreamToWriteableBitmap(IRandomAccessStream stream)
        {   
            // initialize with 1,1 to get the current size of the image
            var writeableBmp = new WriteableBitmap(1, 1);
            writeableBmp.SetSource(stream);

            // and create it again because otherwise the WB isn't fully initialized and decoding
            // results in a IndexOutOfRange
            writeableBmp = new WriteableBitmap(writeableBmp.PixelWidth, writeableBmp.PixelHeight);

            stream.Seek(0);
            writeableBmp.SetSource(stream);

           return writeableBmp;
        }

Y cuidadito si se les olvida el .Seek(0).

De esta manera he conseguido solucionar el error de convertir un IRandomAccesStream to WriteableBitmap para poder guarda

Bueno, se preguntaran ¿Y que hago con un WriteableBitmap?.

Pues surgió de la necesidad de guardar una hoja de un pdf a imagen con una resolución mayor.

Aquí el código para ello.

public async Task SaveToFile(WriteableBitmap writeableBitmap, IStorageFile outputFile)
        {
            try
            {
                var stream = writeableBitmap.PixelBuffer.AsStream();

                var pixels = new byte[(uint)stream.Length];
                await stream.ReadAsync(pixels, 0, pixels.Length);

                using(var streamOut = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, streamOut);
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, 96, 96, pixels);

                    await encoder.FlushAsync();

                    using(var outputStream = streamOut.GetOutputStreamAt(0))
                    {
                        await outputStream.FlushAsync();
                    }
                }
            }
            catch(Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

© 2024 vladymix | WordPress Theme: Annina Free by CrestaProject.