Skip navigation

Generating new images on the fly in .Net

Imaging or graphics has long been a hard topic in Windows programming because of the inherently difficult Win32 model. It is no longer the case with .Net. System.Drawing and System.IO namesapces provide powerful enabling classes to wrap around GDI+ device drawing technology, so now we can do real magical things with a lot less effort. I guess rule #1 for .Net programming would be "Remember, .Net does the heavy lifting for you".

What we are going to see today is how to crop/resize an existing image, then save it as thumbnail like image. This functionality is especially useful if you have a web site, and you need to maintain smaller images of an original larger images to provide links to documents. We at MSD2D uses these code to maintain our images, it saves the repetitive, boring cropping and resizing, "save as" operation, and you don't even need a PhotoShop for this.

The basic steps involved here are:

1. Open a file which contains the image you want to crop/resize

2. Select the portion you want to keep by specifying the source rectangle area in the original image

3. Specify how big the result image you want by specifying a destination rectangle

4. Draw the new image onto the GDI+ device context using the encapsulating Graphics object.

5. Save your new image into a file, MemoryStream, or even network stream

First let's see the screen shot of what we are going to accomplish today, the application will display the image you choose from the open file menu, then display in two preview sizes (smaller images), you can save it the first one to your desired location:

Important code highlight

public void drawPreview(){

System.Drawing.Bitmap bmp_Summary = new System.Drawing.Bitmap(60, 82);
System.Drawing.Rectangle sourceRect = new System.Drawing.Rectangle(
startP.X,
startP.Y,
75,
100);

System.Drawing.Rectangle destRect =
new System.Drawing.Rectangle(
0, 0, 60, 82);
 

Graphics gprx = Graphics.FromImage(bmp_Summary);
gprx.DrawImage(original, destRect, sourceRect, GraphicsUnit.Pixel);
gprx.Dispose();

pictureBox1.Image = bmp_Summary;

}

startP is the point you clicked on the image using your mouse. The clipping starts where you clicked. Source code for this ImageClipper application is attached, feel free to download.The same code can be used in a web application. Place it in a page or HttpHandler, then it can generate dynamic images. Note that since the output stream is binary, which cannot be mixed with text stream, the imagary output has to be the only output of that page or .ashx file, then reference the file using "src" or other linking attribute of other controls.

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish