Resize an image to view its pixels in C#

[resize an image]

This example shows how to resize an image so it is big enough to view its pixels. Normally you want resized images to be smooth, but this technique can be useful if you want to see exactly what colors the pixels contain. For example, if you’re making an image editing tool, this lets you click on the enlarged pixels to modify them individually.

The basic idea is to use the Graphics object’s DrawImage method to draw the image at an enlarged size. The only catch is that by default the method smooths the result. To make the pixels stand out clearly, you need to set the object’s InterpolationMode property.

When you select a scale from the combo box, the program uses the following code to display the image at the selected scale.

// Display the image at the selected size.
private void cboScale_SelectedIndexChanged(
    object sender, EventArgs e)
    // Get the scale.
    float scale = float.Parse(cboScale.Text);

    // Make a bitmap of the right size.
    int wid = (int)(picOriginal.Image.Width * scale);
    int hgt = (int)(picOriginal.Image.Height * scale);
    Bitmap bm = new Bitmap(wid, hgt);
    // Draw the image onto the new bitmap.
    using (Graphics gr = Graphics.FromImage(bm))
        // No smoothing.
        gr.InterpolationMode = InterpolationMode.NearestNeighbor;

        Point[] dest =
            new Point(0, 0),
            new Point(wid, 0),
            new Point(0, hgt),
        Rectangle source = new Rectangle(
            0, 0,
            dest, source, GraphicsUnit.Pixel);

    // Display the result.
    picScaled.Image = bm;

This code parses the scale selected in the combo box. It then calculates the image’s scaled width and height, and makes a bitmap with the scaled size.

Next the program creates a Graphics object associated with the bitmap and sets its InterpolationMode property to NearestNeighbor. That makes the object not smooth results when it must resize an image.

The code then creates a destination rectangle that will fill the bitmap. It also creates a source array of points that define the upper left, upper right, and lower left corners of the original image. The program then calls the Graphics object’s DrawImage method to draw the image onto the bitmap.

The program finishes by displaying the bitmap.

Download Example   Follow me on Twitter   RSS feed   Donate

About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in graphics, image processing and tagged , , , , , , , , , , , . Bookmark the permalink.