调整图像大小但仍有大量字节(UWP)

时间:2016-10-17 10:28:51

标签: c# xamarin uwp

我有这个代码可以调整存储文件的图像大小:

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();
    }
}

问题在于,即使调整大小也会继续输入字节数,例如,如果一个图像Enviu I 4MB,它会继续输出到4MB。

1 个答案:

答案 0 :(得分:2)

您将缩放后的图像写回原始文件,这意味着您将缩放后的图像写入原始文件的前X个字节,其余部分保持不变。

输出到新文件或将源文件读入内存并使用CreationCollisionOption of ReplaceExisting

重新创建输出文件