调整图像大小,但仍然有很多字节(UWP)
本文关键字:多字节 UWP 图像 调整 | 更新日期: 2023-09-27 18:13:19
我有这段代码来调整存储文件的图像大小:
var file = await ImageChooser.GetSelectedImageAsStorageFile();
using (var sourceStream = await file.OpenAsync(FileAccessMode.Read))
{
int maxWidth = 500, maxHeight = 500;
BitmapImage sourceImage = new BitmapImage();
sourceImage.SetSource(sourceStream);
var origHeight = sourceImage.PixelHeight;
var origWidth = sourceImage.PixelWidth;
var ratioX = maxWidth / (float)origWidth;
var ratioY = maxHeight / (float)origHeight;
var ratio = Math.Min(ratioX, ratioY);
var newHeight = (uint)(origHeight * ratio);
var newWidth = (uint)(origWidth * ratio);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);
BitmapTransform transform = new BitmapTransform() { ScaledHeight = newHeight, ScaledWidth = newWidth };
PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Rgba8,
BitmapAlphaMode.Straight,
transform,
ExifOrientationMode.RespectExifOrientation,
ColorManagementMode.DoNotColorManage);
using (var destinationStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var propertySet = new BitmapPropertySet();
var qualityValue = new BitmapTypedValue(0.3, PropertyType.Single);
propertySet.Add("ImageQuality", qualityValue);
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destinationStream, propertySet);
encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, newWidth, newHeight, 96, 96, pixelData.DetachPixelData());
await encoder.FlushAsync();
}
}
问题是,即使调整大小也会随着输入字节的数量而继续,例如,如果一个图像是4MB,它会继续将输出字节的大小调整为4MB。
您正在将缩放后的图像写入原始文件,这意味着您正在将缩放后的图像写入原始文件的前X个字节,而其余部分保持不变。
输出到新文件或将源文件读入内存并使用ReplaceExisting
的CreationCollisionOption
重新创建输出文件