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.