I am converting png to Jpeg using this code but it is getting stuck on encoder.FlushAsync() and never returns. I have tried several ways to resolve this but nothing works. encoder.FlushAsync() doesn't even give exceptions. Without await debug gets passed but the image is not correct and with await, application freezed. I have mentioned the link and code below:
public async Task<Stream> ConvertPngToJpeg2(Stream s)
{
byte[] resultArray = null;
//Convert stream into byte array
byte[] image = new byte[s.Length];
s.Read(image, 0, image.Length);
//Create An Instance of WriteableBitmap object
WriteableBitmap resultBitmap = new WriteableBitmap(1, 1);
using (IRandomAccessStream ms = new InMemoryRandomAccessStream())
{
await ms.WriteAsync(image.AsBuffer());
ms.Seek(0);
//Set the source for WriteableBitmap
resultBitmap.SetSource(ms);
}
//Get the image data
using (IRandomAccessStream ms = new InMemoryRandomAccessStream())
{
try
{
byte[] bytes;
// Open a stream to copy the image contents to the WriteableBitmap's pixel buffer
using (Stream stream = resultBitmap.PixelBuffer.AsStream())
{
bytes = new byte[(uint)stream.Length];
await stream.ReadAsync(bytes, 0, bytes.Length);
}
// Create an encoder with the Jpeg format
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ms);
// WriteableBitmap uses BGRA format
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)resultBitmap.PixelWidth, (uint)resultBitmap.PixelHeight, 96, 96, bytes);
//Terminate the encoder bytes
await encoder.FlushAsync();
resultArray = new byte[ms.AsStream().Length];
await ms.AsStream().ReadAsync(resultArray, 0, resultArray.Length);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
//Store the image into memory stream
Stream imgStream = new MemoryStream(resultArray);
//Return the Jpeg image as stream
return imgStream;
}
gone through some links: BitmapEncoder FlushAsync() never returns BitmapEncoder FlushAsync throws Argument Exception - c#