如何使用 C# WinRT 调整图像大小

How to resize an image with c# WinRT

几周前,我开始开发我的第一个 windows app metro Visual Studio 2015。我注意到有些主题不容易找到明确的信息。

我正在尝试调整(缩小)我之前保存在文件系统中的图像,然后将其保存到另一个文件夹。

我发现 this thread 他们在谈论这个。我已经修改了他们共享的代码,但结果图像对我来说是不可接受的。因为,我可以看到图像的结果似乎是"pixel points",特别是图像的细节。我不知道如何描述结果图像...就像使用旧的画笔应用程序一样,当我们更改图像尺寸时。

我做错了什么?为什么会这样?

我考虑过使用 NuGet 包作为替代方案,以更轻松地完成这项工作。在这种情况下,存在一些用于此任务的不错的 NuGet 包,并且能够在 c# Visual Studio 2015?

中工作

我要分享我的代码功能:

注意:新尺寸与原始图像成比例,我使用的是 PNG 图像。

     public async static Task<bool> ResizeImage(Windows.Storage.StorageFile sourceFile, Windows.Storage.StorageFile destinationFile, int newWidth, int newHeight, int dpi)
{
    try
    {
        using (var sourceStream = await sourceFile.OpenAsync(FileAccessMode.Read))
        {
            Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(sourceStream);
            Windows.Graphics.Imaging.BitmapTransform transform = new Windows.Graphics.Imaging.BitmapTransform() { ScaledHeight = Convert.ToUInt32(newHeight), ScaledWidth = Convert.ToUInt32(newWidth) };
            Windows.Graphics.Imaging.PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                Windows.Graphics.Imaging.BitmapPixelFormat.Rgba8,
                BitmapAlphaMode.Straight,
                transform,
                ExifOrientationMode.RespectExifOrientation,
                ColorManagementMode.DoNotColorManage);

            using (var destinationStream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream);
                encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, Convert.ToUInt32(newWidth), Convert.ToUInt32(newHeight), Convert.ToUInt32(dpi), Convert.ToUInt32(dpi), pixelData.DetachPixelData());
                await encoder.FlushAsync();
            }
        }
    }
    catch (Exception ex)
    {
        ModuleLog.WriteError(ex.ToString());
        return false;
    }

    return true;
}

注意:我正在尝试缩小图像的大小。例如,我有一个100 x 100像素的原始文件图像,我想获得一个50 x 50像素的文件图像。

我想我已经找到了解决办法。

我在函数中添加了这一行:

transform.InterpolationMode = BitmapInterpolationMode.Fant;

BitmapTransform 具有 InterpolationMode 属性,您可以指定我们在调整图像大小时要使用的插值类型。

Here你可以看到所有的可能性。

就我而言,我注意到使用 "Fant" 插值是获得最佳图像结果的最佳方法。