如何在 Windows 10 UWP 中复制和调整图像大小

How to Copy and Resize Image in Windows 10 UWP

我已经使用 http://www.codeproject.com/Tips/552141/Csharp-Image-resize-convert-and-save 中的代码以编程方式调整图像大小。但是,该项目使用 System.Drawing 库,Windows 10 个应用程序无法使用这些库。

我尝试使用 Windows.UI.Xaml.Media.Imaging 中的 BitmapImage class,但它似乎没有提供 System.Drawing 中的功能..

有没有人能够在 Windows 10 中调整(缩小)图像的大小?我的应用程序将处理来自不同 formats/sizes 的多个来源的图像,我正在尝试调整实际图像的大小以保存 space,而不是让应用程序调整大小以适应 Image ] 在其中显示它。

编辑

我修改了上面提到的 link 的代码,并且有一个 hack 可以满足我的特定需要。这是:

public static BitmapImage ResizedImage(BitmapImage sourceImage, int maxWidth, int maxHeight)
{
    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;
}

这种方法似乎可行,但理想情况下,与其修改原始 BitmapImage,我想创建一个 new/copy 来修改 return。

这是它的实际截图:

I may want to return a copy of the original BitmapImage rather than modifying the original.

没有什么好的方法可以直接复制一个BitmapImage,但是我们可以多次复用StorageFile

如果你只想select一张图片,显示它,同时显示原始图片调整大小的图片,你可以像这样传递StorageFile作为参数:

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

在这种情况下,您只需调用此任务并显示调整大小后的图像,如下所示:

smallImage.Source = await ResizedImage(file, 250, 250);

如果你因为某些原因想要保留BitmapImage参数(比如sourceImage可能是一个修改过的位图但不是直接从文件加载),并且你想将这张新图片重新调整大小一,你需要先将调整大小的图片保存为一个文件,然后打开这个文件并重新调整大小。