GDI+图像加载效率

本文关键字:效率 加载 图像 GDI+ | 更新日期: 2023-09-27 17:54:34

现有的应用程序加载了大量的图像缩略图,并在画布(GDI+ Graphics对象)中旋转/定位它们。

它这样做的方式不是很有效,但还可以,直到我们有一个功能请求,添加缩放变换到图像。

当前代码看起来像

//Images is a collection of ImgInfo, a user defined class
//contains the width, height, offsets, scale factors, and rotation
//in addition to a Bitmap thumbnail.
foreach (var imgInfo in Images)
{
    var imgRect = new Rectangle(0, 0, imgInfo.Width, imgInfo.Height);
    int dx = imgInfo.XOffset, dy = imgInfo.YOffset;
    //Transform the canvas to the drawing coordinate system
    graphics.TranslateTransform(dx, dy);
    graphics.ScaleTransform(1 / (float)imgInfo.ScaleX, 1 / (float)imgInfo.ScaleY);
    graphics.RotateTransform(-imgInfo.Rotation);
    //Center the image
    graphics.TranslateTransform(-imgInfo.Width / 2, -imgInfo.Height / 2);
    graphics.DrawImage(imgInfo.Thumbnail, imgRect);
    //Transform back to the display coordinate system
    graphics.TranslateTransform(imgInfo.Width / 2, imgInfo.Height / 2);
    graphics.RotateTransform(imgInfo.Rotation);
    graphics.ScaleTransform((float)imgInfo.ScaleX, (float)imgInfo.ScaleY);
    graphics.TranslateTransform(-dx, -dy);
}

我认为原因如下。假设我有1000个缩略图,绘制第999个缩略图将导致翻译、旋转和缩放到目前为止绘制的所有998个图像。这并不是那么糟糕,只要我们不使用缩放变换-(我猜系统已经优化旋转)。

那么问题是,如何优化这个?

GDI+图像加载效率

原来这个问题不是尺度变换。问题是代码在GUI呈现期间引入了一个异常。由于异常处理是扩展的,因此我们有上述性能问题。直到我们检查日志,我们才意识到这个问题,因为代码必须在GUI呈现异常后继续,所以没有明显的异常发生的迹象。