微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 图像调整大小的性能:System.Drawing与System.Windows.Media

我有一个需要调整大量图像大小的情况.这些图像当前存储在文件系统上的.jpg文件,但是我期望在项目中稍后会有内存中的byte [].源图像尺寸是可变的,但输出应为3种不同的预定尺寸.应保留长宽比,填充原始图像为白色空间(即,一个真正高的图像将被调整大小以适应在正方形目标图像大小内,左侧和右侧有大面积的白色).

我最初构建了面向.NET 2.0的项目,并使用System.Drawing类来执行load / resize / save.相关代码包括

original = Image.FromFile(inputFile); //NOTE: Reused for each of the 3 target sizes
Bitmap resized = new Bitmap(size,size);
//Draw the image to a new image of the intended size
Graphics g = Graphics.FromImage(resized);
g.InterpolationMode = System.Drawing.drawing2d.InterpolationMode.HighQualityBicubic;
g.Clear(Color.White);
g.DrawImage(original,center - width / 2f,center - height / 2f,width,height);
g.dispose();
//Save the new image to the output path
resized.Save(outputFile,ImageFormat.Jpeg);

我想将此项目移植到.NET 3.5,所以尝试使用System.Windows.Media类来执行相同的功能.我得到它的工作,但表现是可怕的;每张图片的处理时间约为50倍.绝大多数时间都是加载图像.相关代码包括

BitmapImage original = new BitmapImage(); //Again,reused for each of the 3 target sizes
original.BeginInit();
original.StreamSource = new MemoryStream(imageData); //imageData is a byte[] of the data loaded from a FileStream
original.CreateOptions = BitmapCreateOptions.None;
original.CacheOption = BitmapCacheOption.Default;
original.EndInit(); //Here's where the vast majority of the time is spent
original.Freeze();

// Target Rect for the resize operation
Rect rect = new Rect(center - width / 2d,center - height / 2d,height);

// Create a DrawingVisual/Context to render with
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.Renderopen())
{
    drawingContext.DrawImage(original,rect);
}

// Use rendertargetBitmap to resize the original image
rendertargetBitmap resizedImage = new rendertargetBitmap(
    size,size,// Resized dimensions
    96,96,// Default DPI values
    PixelFormats.Default);              // Default pixel format
resizedImage.Render(drawingVisual);

// Encode the image using the original format and save the modified image
SaveImageData(resizedImage,outputFile);

在这里做错了什么,要花太多时间?我已经尝试使用BitmapImage上的构造函数,该构造函数使用了URI,那里也是一样的性能问题.任何人以前都做过这样的事情,知道是否有更多的表现方式来做到这一点?还是我还需要使用System.Drawing?谢谢!

解决方法

在打完所有这些之后,发生在我身上,我可以从MS加载System.Windows.Media类的符号,然后逐步缓慢.立即找到原因和解决办法.输入图像被保存为一个颜色配置文件,并尝试加载每个图像的颜色配置文件(从文件系统).通过在上面的代码中从BitmapCreateOptions.None切换到BitmapCreateOptions.IgnoreColorProfile,它不再这样做,并且与System.Drawing一样快.

希望这能帮助任何遇到这个问题的人!

原文地址:https://www.jb51.cc/csharp/92586.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐