I am developing Windows 8 app. I want to get resized image as byte. So my method will get StorageFile, height & width and it will return me byte[] or resized image. What I've tries so far is given below. My efforts returns me byte[] with all values as 0.
PS : I don't want to create new resized StorageFile & also don't want to use WritableBitmapEx for only one method.
private async Task<byte[]> ResizeImage(StorageFile BigFile, uint finalHeight, uint finalWidth)
{
using (var sourceStream = await BigFile.OpenAsync(FileAccessMode.Read))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);
BitmapTransform transform = new BitmapTransform() { ScaledHeight = finalHeight, ScaledWidth = finalWidth };
PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Rgba8,
BitmapAlphaMode.Straight,
transform,
ExifOrientationMode.RespectExifOrientation,
ColorManagementMode.DoNotColorManage);
InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ras);
encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, finalWidth, finalHeight, 96, 96, pixelData.DetachPixelData());
await encoder.FlushAsync();
var bb = new byte[ras.Size];
await ras.ReadAsync(bb.AsBuffer(), (uint)ras.Size, InputStreamOptions.None);
return bb;
}
}
From the PixelDataProvider class at MSDN:
An application asynchronously receives a PixelDataProvider from the GetPixelDataAsync methods of BitmapFrame or BitmapDecoder. The application can then synchronously request the pixel data using DetachPixelData to get access to the raw pixels of the bitmap.
What that means is that you just need to call DetachPixelData on the PixelDataProvider object:
private async Task<byte[]> ResizeImage(StorageFile BigFile, uint finalHeight, uint finalWidth)
{
using (var sourceStream = await BigFile.OpenAsync(FileAccessMode.Read))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);
BitmapTransform transform = new BitmapTransform() { ScaledHeight = finalHeight, ScaledWidth = finalWidth };
PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Rgba8,
BitmapAlphaMode.Straight,
transform,
ExifOrientationMode.RespectExifOrientation,
ColorManagementMode.DoNotColorManage);
byte[] buffer = pixelData.DetachPixelData();
return buffer;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With