我有一个需要调整大量图像大小的情况.这些图像当前存储在文件系统上的.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?谢谢!
解决方法
@H_404_15@ 在打完所有这些之后,发生在我身上,我可以从MS加载System.Windows.Media类的符号,然后逐步缓慢.立即找到原因和解决办法.输入图像被保存为一个颜色配置文件,并尝试加载每个图像的颜色配置文件(从文件系统).通过在上面的代码中从BitmapCreateOptions.None切换到BitmapCreateOptions.IgnoreColorProfile,它不再这样做,并且与System.Drawing一样快.希望这能帮助任何遇到这个问题的人!