在不失透明度的情况下调整UWP项目中的PNG大小?

时间:2017-01-20 07:24:51

标签: uwp

我想调整通用Windows项目中透明的PNG图像,但我失去了透明度。 与Stack Overflow网站的这篇文章类似。 Why does resizing a png image lose transparency? 我已经在Stack Overflow中检查了与我的问题相关的所有文章,但没有一个有正确的答案。 谁能帮我解决一下呢?

public static async Task<BitmapImage> ResizedImage(StorageFile ImageFile, int maxWidth, int maxHeight)
{

    IRandomAccessStream inputstream = await ImageFile.OpenReadAsync();
    BitmapImage sourceImage = new BitmapImage();
    sourceImage.SetSource(inputstream);
    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 = (int)(origHeight * ratio);
    var newWidth = (int)(origWidth * ratio);

    sourceImage.DecodePixelWidth = newWidth;
    sourceImage.DecodePixelHeight = newHeight;

    return sourceImage;

} 

1 个答案:

答案 0 :(得分:0)

您正在失去透明度,因为您正在转换为位图,并且位图不支持透明度。您需要使用支持透明度的格式。

这是一段将采用PNG并在不失去透明度的情况下调整大小的代码

private async void MakeSmaller(StorageFile inputFile, StorageFile outputFile)
{
    using (var inputStream = await inputFile.OpenAsync(FileAccessMode.Read))
    {
        var decoder = await BitmapDecoder.CreateAsync(inputStream);

        var softwareBitmap = await decoder.GetSoftwareBitmapAsync();

        using (var outputStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
        {
            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId,
                                                          outputStream);

            encoder.SetSoftwareBitmap(softwareBitmap);
            encoder.BitmapTransform.ScaledWidth = 50;
            encoder.BitmapTransform.ScaledHeight = 50;
            encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;

            await encoder.FlushAsync();
        }
    }
}