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

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

我尝试使用Windows.UI.Xaml.Media.ImagingBitmapImage类,但它似乎没有提供在System.Drawing中找到的function。

有没有人能够在Windows 10中resize(缩小)图像? 我的应用程序将处理来自多个源,不同格式/大小的图像,我试图调整实际图像的大小以节省空间,而不是让应用程序resize以适应显示它的图像。

编辑

我已经修改了上面提到的链接中的代码,并且有一个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 ,我想创建一个新的/副本来修改和返回。

以下是它的实际应用: 调整大小图像的屏幕截图

我可能想要返回原始BitmapImage的副本,而不是修改原始。

直接复制BitmapImage没有好方法,但我们可以多次重复使用StorageFile

如果你只想选择一张图片,然后显示它,同时显示原始图片的重新resize的图片,你可以将StorageFile作为参数传递给你:

 public static async Task 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; } 

在这种情况下,您只需调用此任务并显示重新resize的图像,如下所示:

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

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