我正在使用此代码将png转换为Jpeg,但它卡住了encoder.FlushAsync()并且永远不会返回。我已经尝试了几种方法来解决这个问题,但没有任何效果。encoder.FlushAsync()甚至不给出异常。没有await,调试通过,但图像不正确,使用await,应用程序冻结。我已经提到了下面的链接和代码:
https://www.syncfusion.com/kb/7918/how-to-convert-jpeg-image-from-png-image-and-draw-those-jpeg-image-into-pdf-document
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;
}
通过一些链接:BitmapEncoder FlushAsync()永远不会返回BitmapEncoder FlushAsync抛出参数异常- c#
我们附上了可运行的样品供您参考。请在您那边试一下,然后告诉我们结果。
示例:https://www.syncfusion.com/downloads/support/directtrac/general/ze/uwp_sample - 1957906502