8
我有一個JPEG圖像存儲在我想調整大小的字節[]中。這是我的代碼:UWP:如何調整圖像大小
public async Task<byte[]> ResizeImage(byte[] imageData, int reqWidth, int reqHeight, int quality)
{
var memStream = new MemoryStream(imageData);
IRandomAccessStream imageStream = memStream.AsRandomAccessStream();
var decoder = await BitmapDecoder.CreateAsync(imageStream);
if (decoder.PixelHeight > reqHeight || decoder.PixelWidth > reqWidth)
{
using (imageStream)
{
var resizedStream = new InMemoryRandomAccessStream();
BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);
double widthRatio = (double) reqWidth/decoder.PixelWidth;
double heightRatio = (double) reqHeight/decoder.PixelHeight;
double scaleRatio = Math.Min(widthRatio, heightRatio);
if (reqWidth == 0)
scaleRatio = heightRatio;
if (reqHeight == 0)
scaleRatio = widthRatio;
uint aspectHeight = (uint) Math.Floor(decoder.PixelHeight*scaleRatio);
uint aspectWidth = (uint) Math.Floor(decoder.PixelWidth*scaleRatio);
encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear;
encoder.BitmapTransform.ScaledHeight = aspectHeight;
encoder.BitmapTransform.ScaledWidth = aspectWidth;
await encoder.FlushAsync();
resizedStream.Seek(0);
var outBuffer = new byte[resizedStream.Size];
uint x = await resizedStream.WriteAsync(outBuffer.AsBuffer());
return outBuffer;
}
}
return imageData;
}
問題是outBuffer只包含零,儘管已經寫入了正確的字節數。
非常感謝。這有點直觀而且在線文檔並不足夠 – Thomas