【发布时间】:2016-07-27 15:48:03
【问题描述】:
我正在尝试调整我的 UWP 应用程序中的图像大小。大多数情况下,附加代码有效,但有时await encoder.FlushAsync(); 会抛出ArgumentException。
我已经前往 MSDN (https://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmapencoder.bitmaptransform.aspx),他们告诉我(在“备注”处):
如果您尝试使用 BitmapTransform 成员缩放以索引像素格式存储的图像,FlushAsync 将失败并显示 HRESULT WINCODEC_ERR_INVALIDPARAMETER 。相反,您必须使用 GetPixelDataAsync 获取缩放后的像素数据,然后使用 SetPixelData 在编码器上进行设置。
我已经尝试过这样做,请参阅两行注释(由于重复,我觉得这有点不对劲)。在第二行(我尝试SetPixelData),编码器以buffer allocated not sufficient 异常奖励我。
var decoder = await BitmapDecoder.CreateAsync(streamToReadFrom.AsStream().AsRandomAccessStream());
if (decoder.OrientedPixelHeight > height ||
decoder.OrientedPixelWidth > width)
{
var resizedStream = new InMemoryRandomAccessStream();
BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);
encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
encoder.BitmapTransform.ScaledHeight = newHeight;
encoder.BitmapTransform.ScaledWidth = newWidth;
//"buffer allocated not sufficient"
// var pd = await decoder.GetPixelDataAsync(BitmapPixelFormat.Rgba16, BitmapAlphaMode.Ignore,
// encoder.BitmapTransform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);
// encoder.SetPixelData(BitmapPixelFormat.Rgba16, BitmapAlphaMode.Ignore,
// decoder.OrientedPixelWidth, decoder.OrientedPixelHeight, decoder.DpiX, decoder.DpiY, pd.DetachPixelData());
// write out to the stream
// might fail cause https://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmapencoder.bitmaptransform.aspx
await encoder.FlushAsync();
// Read out resizedStream and return
}
导致此问题的示例图像:http://www.spiegel.de/images/image-1028227-hppano-lqbn.jpg。单元测试在这里:https://github.com/famoser/OfflineMedia/blob/master/Famoser.OfflineMedia.UnitTests/Presentation/ImageResizeTest.cs
如何避免ArgumentException?我如何知道图像是“索引像素格式”,以及如何调整这种格式的大小?
【问题讨论】:
标签: c# uwp bitmapencoder