I got RenderTargetBitmap object. I like to manipulate image and Bind to Image control.
So, I created the following method to do imgCtrl.Source = await CropRedrawImage(renderTargetSourceImg);
However, SoftwareBitmap.CreateCopyFromBuffer or/and CanvasBitmap.CreateFromSoftwareBitmap throws exception.
CreateFromSoftwareBitmap throws "'The bitmap pixel format is unsupported."
CreateCopyFromBuffer throws 'Insufficient memory for response' for Rgba16 type.
How to avoid the exception and get the method worked?
async Task<BitmapImage> CropRedrawImage(RenderTargetBitmap sourceImg)
{
float dpi = 96;
using (CanvasDevice device = CanvasDevice.GetSharedDevice())
{
using (var renderTarget = new CanvasRenderTarget(device,
sourceImg.PixelWidth, sourceImg.PixelHeight, dpi))// dpi); if it use dpi other than 96, it resizes.
{
using (var ds = renderTarget.CreateDrawingSession())
{
Windows.Storage.Streams.IBuffer buffer = await sourceImg.GetPixelsAsync();
SoftwareBitmap bitmap = SoftwareBitmap.CreateCopyFromBuffer(buffer, BitmapPixelFormat.Bgra8, sourceImg.PixelWidth, sourceImg.PixelHeight);
//BitmapPixelFormat.Rgba8, Bgra8 -> NOT supported format by CanvasBitmap.CreateFromSoftwareBitmap, Rgba16 -> Throw exception,
// Rgba16 -> Throw 'Insufficient memory for response. (Exception from HRESULT: 0xC00D7170)'
CanvasBitmap image = CanvasBitmap.CreateFromSoftwareBitmap(device, bitmap);
//=> Throws System.Exception: 'The bitmap pixel format is unsupported. (Exception from HRESULT: 0x88982F80)'
ds.Clear(Colors.Transparent);
Rect dest = new Rect(0, 0, 100, 100); //Test.
Rect src = new Rect(0, 0, 100, 100);
ds.DrawImage(image, dest, src);
}
//convert CanvasRenderTarget to BitmapImage which is bound to Image control's ImageSource.
BitmapImage bmpImg = new BitmapImage();
using (var stream = new InMemoryRandomAccessStream())
{
await renderTarget.SaveAsync(stream, CanvasBitmapFileFormat.Png);
stream.Seek(0);
await bmpImg.SetSourceAsync(stream);
}
return bmpImg;
}
}
}