How to: Improve Performance by Avoiding Automatic Scaling

GDI+ may automatically scale an image as you draw it, which would decrease performance. Alternatively, you can control the scaling of the image by passing the dimensions of the destination rectangle to the DrawImage method.

For example, the following call to the DrawImage method specifies an upper-left corner of (50, 30) but does not specify a destination rectangle.

e.Graphics.DrawImage(image, 50, 30);  // upper-left corner at (50, 30)
e.Graphics.DrawImage(image, 50, 30) ' upper-left corner at (50, 30)

Although this is the easiest version of the DrawImage method in terms of the number of required arguments, it is not necessarily the most efficient. If the resolution used by GDI+ (usually 96 dots per inch) is different from the resolution stored in the Image object, then the DrawImage method will scale the image. For example, suppose an Image object has a width of 216 pixels and a stored horizontal resolution value of 72 dots per inch. Because 216/72 is 3, DrawImage will scale the image so that it has a width of 3 inches at a resolution of 96 dots per inch. That is, DrawImage will display an image that has a width of 96x3 = 288 pixels.

Even if your screen resolution is different from 96 dots per inch, GDI+ will probably scale the image as if the screen resolution were 96 dots per inch. That is because a GDI+ Graphics object is associated with a device context, and when GDI+ queries the device context for the screen resolution, the result is usually 96, regardless of the actual screen resolution. You can avoid automatic scaling by specifying the destination rectangle in the DrawImage method.

Example

The following example draws the same image twice. In the first case, the width and height of the destination rectangle are not specified, and the image is automatically scaled. In the second case, the width and height (measured in pixels) of the destination rectangle are specified to be the same as the width and height of the original image. The following illustration shows the image rendered twice:

Screenshot that shows images with scaled texture.

Image image = new Bitmap("Texture.jpg");

e.Graphics.DrawImage(image, 10, 10);
e.Graphics.DrawImage(image, 120, 10, image.Width, image.Height);
Dim image As New Bitmap("Texture.jpg")

e.Graphics.DrawImage(image, 10, 10)
e.Graphics.DrawImage(image, 120, 10, image.Width, image.Height)

Compiling the Code

The preceding example is designed for use with Windows Forms, and it requires PaintEventArgs e, which is a parameter of the Paint event handler. Replace Texture.jpg with an image name and path that are valid on your system.

See also