我正在使用此代码将png转换为jpeg,但它在encoder. FlushAsync()上卡住了,并且永远不会返回。我尝试了几种方法来解决这个问题,但都没有效果。encoder. FlushAsync()甚至没有给出异常。没有等待调试通过,但图像不正确,使用等待,应用程序冻结。我在下面提到了链接和代码:
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() never returnsBitmapEncoder FlushAsync throws Argument Exception - c#
1条答案
按热度按时间brqmpdu11#
我们已附上可运行的样本供您参考。请在您的一端尝试这个,并让我们知道结果。
样品:https://www.syncfusion.com/downloads/support/directtrac/general/ze/UWP_Sample-1957906502