GDI+ image loading efficiency

93 views Asked by At

The existing application loads a lot of image thumbnails and rotating/positioning them in a canvas (a GDI+ Graphics object).

The way it does this is not very efficient but is OK until we have a feature request that to add a scaling transform to the images.

The current code looks like

//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);
}

The reason of this I suspect, is the following. Suppose I have 1000 thumbnails, drawing the 999th thumbnail will result in translating, rotating, and scaling all the 998 images drawn so far. This is not so bad as long as we do not use scale transform - (I guess the system have optimized for rotations).

So the question is, what is the way to optimize this?

1

There are 1 answers

0
Earth Engine On

It turn out that this issue is not the scale transform. The problem is that the code introduced an exception during GUI rendering. Since exception handling is expansive, we have the above performance issue. Until we checked the log we didn't realize this problem because the code have to continue after exception in GUI rendering and so there is no apparent signs for exception being occurred.