Title: Resize an image to view its pixels in C#
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(
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 the example to experiment with it and to see additional details.