How resize an image using GDI+

June 11, 2011 - 06:19

Resizing of images is very important when designing web applications, as you don't really want to have 4 megabyte images displayed on your web pages. Ideally you want to create a thumbnail image of those, and display that. When the user clicks on this image, then display original Image.

This example demonstrates how to resize an image to make it fit in a specifed box size and then save this image back.

It assumes that your original images are stored in "/original" and the created thumbs will be stored in "/thumbs".

<%@ Import Namespace="" %>
<%@ Import Namespace="system.drawing" %>

Dim thumbimage as bitmap
Dim originalimage as bitmap

Dim width as integer = 200 '# this is the max width of the new image
Dim height as integer = 200 '# this is the max height of the new image
Dim newwidth as integer
Dim newheight as integer

originalimage = system.drawing.Image.FromFile(server.mappath("original/myimage.jpg"))

if originalimage.width>originalimage.height
newheight=originalimage.height/originalimage.width * height
newheight = height
newwidth=originalimage.width/originalimage.height * width
end if

thumbimage = New Bitmap(newwidth, newheight)

Dim gr As Graphics = Graphics.FromImage(thumbimage)
gr.DrawImage(originalimage, 0, 0, newwidth, newheight)


What this code does is take the original image, from this calculate the dimentions for the new image, then create a new image with those dimentions and paste the original image into this graphic. Finally save this out to the "/thumb" directory.

Please remember to make sure you have write permission on the "/thumb" directory.

© 2011