Search code examples
uwpwriteablebitmapwriteablebitmapex

UWP Encode WriteableBitmap to JPEG byte array


I'm trying to encode WriteableBitmap to JPEG byte array. But actually I found examples with the SaveJpeg method which does not exist now. So I tried the ToStreamAsJpeg method but this method does not work. With the step by step I don't get out of it. Thanks


Solution

  • Okay, so I solved my issue with the following method:

    private async Task<byte[]> EncodeJpeg(WriteableBitmap bmp)
    {
        SoftwareBitmap soft = SoftwareBitmap.CreateCopyFromBuffer(bmp.PixelBuffer, BitmapPixelFormat.Bgra8, bmp.PixelWidth, bmp.PixelHeight);
        byte[] array = null;
    
        using (var ms = new InMemoryRandomAccessStream())
        {
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms);
            encoder.SetSoftwareBitmap(soft);
    
            try
            {
                await encoder.FlushAsync();
            }
            catch { }
    
            array = new byte[ms.Size];
            await ms.ReadAsync(array.AsBuffer(), (uint)ms.Size, InputStreamOptions.None);
        }
    
        return array;
    }
    

    Also, if you have a best implementation... ;-)