0
votes

I am encoding a Canvas control which contains Textblocks as child using the following code but I get

The buffer allocated is insufficient

My code

using(InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream())
{
    var displayInformation = DisplayInformation.GetForCurrentView();
    var renderTargetBitmap = new RenderTargetBitmap();
    await renderTargetBitmap.RenderAsync(Textify.CanvasControl);
    var width = renderTargetBitmap.PixelWidth;
    var height = renderTargetBitmap.PixelHeight;
    IBuffer textBuffer = await renderTargetBitmap.GetPixelsAsync();
    byte[] pixels = textBuffer.ToArray();

    //Encode text to PNG
    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ras);

    encoder.SetPixelData(BitmapPixelFormat.Rgba16,
                         BitmapAlphaMode.Premultiplied,
                         (uint)width, 
                         (uint)height,
                         displayInformation.LogicalDpi,
                         displayInformation.LogicalDpi,
                         pixels);

    await encoder.FlushAsync();
...

I know it's the byte[] pixels buffer that is no large enough as I want to encode to BitmapPixelFormat.Rgba16. I do not encounter the error when encoding to BitmapPixelFormat.Rgba8 or BitmapPixelFormat.Bgra8

I tried calculating the buffer using the following but it only produce empty white bitmap.

byte[] pixels = new byte[16 * width * height];

int index = 0;
for (int y = 0; y < height; ++y)
    for (int x = 0; x < width; ++x)
    {
        pixels[index++] = 255;  // B
        pixels[index++] = 255;  // G
        pixels[index++] = 255;  // R
        pixels[index++] = 255;  // A
    }

I want to use BitmapPixelFormat.Rgba16 because I want to improve the image quality. How to do this properly? Thanks.

"I want to use BitmapPixelFormat.Rgba16 because I want to improve the image quality." - That doesn't make sense. Your render target is 32bpp. Trying to go 64bpp in the encoding phase doesn't miraculously improve image quality. It's still 32bpp, with the size requirements of 64bpp.IInspectable
@IInspectable ok fair enough. I might misunderstood the differences between Rgba8 and Rgba16. But how do I improve the PNG encoding quality without going to BitmapPixelFormat.Rgba16 because the quality isn't that good with my current code.PutraKg
PNG is lossless. Whatever goes in comes out. If the quality isn't good, then your input isn't good. The encoded output is an exact replica of the input.IInspectable
@IInspectable In my situation there's still some lost in quality even though I save in PNG. So saying it will fix everything is not the answer I was looking for because it's not.PutraKg
I was looking for options in term of Lumia SDK (in my follow up question), thus the sample code. What you saying is common sense as it appears you have no personal experience in using the SDK.PutraKg