RenderTargetBitmap renders low quality image of the UIElement

Imman Kumar 6 Reputation points
2023-01-17T14:53:16.2+00:00

Hi,

I have a Xamarin.Forms application deployed in UWP, in which I have added Xamarin.Forms.Image to the page and trying to convert the UIElement to image using RenderTargetBitmap, the converted image quality is reduced. Again I have added the converted image to the page as Xamarin.Forms.Image and converting the same again to image with RenderTargetBitmap. The quality of the converted image is degrading progressively when doing this multiple times.

var bitmap = new RenderTargetBitmap();
await bitmap.RenderAsync(element);
var pixelBuffer = await bitmap.GetPixelsAsync();
var pixels = pixelBuffer.ToArray();
var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
using (randomAccessStream = new InMemoryRandomAccessStream())
{
    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, randomAccessStream);
    encoder.SetPixelData(
    BitmapPixelFormat.Bgra8,
    BitmapAlphaMode.Straight,
    (uint)bitmap.PixelWidth,
    (uint)bitmap.PixelHeight,
    logicalDpi,
    logicalDpi,
    pixels);
    await encoder.FlushAsync();
}
Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,274 questions
Universal Windows Platform (UWP)
{count} vote

1 answer

Sort by: Most helpful
  1. Castorix31 81,141 Reputation points
    2023-01-20T10:21:46.8333333+00:00

    You don't need an encoder if you don't save the image to a file

    You can use a WriteableBitmap :

                    RenderTargetBitmap rtb = new RenderTargetBitmap();
                    await rtb.RenderAsync(img1);
                    // Test copy directly the RTB to another Image control
                    // img2.Source = rtb;
                    var pixelBuffer = await rtb.GetPixelsAsync();
                    byte[] pixelArray = pixelBuffer.ToArray();  // BGRA8 format
    
                    var wb = new WriteableBitmap((int)rtb.PixelWidth, (int)rtb.PixelHeight);
                    await wb.PixelBuffer.AsStream().WriteAsync(pixelArray, 0, pixelArray.Length);
                    // Test copy the image to another Image control from WriteableBitmap
                    img2.Source = wb;