dub*_*lee 7 c# image windows-10 windows-10-universal
我使用http://www.codeproject.com/Tips/552141/Csharp-Image-resize-convert-and-save中的代码以编程方式调整图像大小.但是,该项目使用的System.Drawing库是Windows 10应用程序无法使用的.
我尝试过使用BitmapImage该类Windows.UI.Xaml.Media.Imaging,但它似乎没有提供在System.Drawing... 中找到的功能.
有没有人能够在Windows 10中调整大小(缩小)图像?我的应用程序将处理来自多个源,不同格式/大小的图像,我试图调整实际图像的大小以节省空间,而不是让应用程序调整大小以适应Image它的显示位置.
编辑
我已经修改了上面提到的链接中的代码,并且有一个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;
}
Run Code Online (Sandbox Code Playgroud)
这种方式似乎工作,但理想情况下,而不是修改原始BitmapImage,我想创建一个新的/副本来修改和返回.
我可能想要返回原件的副本
BitmapImage而不是修改原件.
直接复制a没有好方法BitmapImage,但我们可以StorageFile多次重复使用.
如果你只是想选择一张图片,显示它,同时显示原始图片的重新调整大小的图片,你可以StorageFile像这样传递as参数:
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;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您只需调用此任务并显示重新调整大小的图像,如下所示:
smallImage.Source = await ResizedImage(file, 250, 250);
Run Code Online (Sandbox Code Playgroud)
如果BitmapImage由于某些原因想要保留参数(例如sourceImage可能是修改后的位图但不是直接从文件加载),并且您想要将这个新图片重新调整为另一个,则需要保存首先将图片调整为文件,然后打开此文件并重新调整大小.