OKCOOL

Back

Resizing images in .NET

There are lots of examples on the Interweb about how to do image resizing in .NET – unfortunately none of these quite hit the mark where we were concerned.

The problem is that you generally need to know both the height and width of a thumbnail so that your XHTML CSS developer doesn’t get too upset and can do a nice layout without having to distort your images.

The following is the start of some C# code I’ve written to do various different resizing of images as follows:

  • ToLargest – the largest dimension is shrunk to the specified size – not yet found a use for this!
  • ToWidth – shrinks the width down to the specified size and makes the height the correct aspect ration, useful for vertical scrolling lists of images.
  • ToHeight – same as width but shrinks the height to the specified size and changes the width, useful for horizontal scrolling lists.
  • ToSquareCanvas – squares the image to the specified dimension and places a correctly shrunk image in to the middle.
  • ToSquareImage – squares the image exactly and doesn’t worry about distorting the original.

The main function ResizeImage takes an image parameter to make it as useful as possible. For example, it’s easy to get an image object from an uploaded file using something like the following:

Here is the entire class for resizing images. Note the public enum which gives the available sizing methods. Also, you can pass the function a hex color e.g. ff0000 which will change the colour of the canvas.

Hope this is helpful to someone, if you have any comments or suggestions let me know

  • Tom
  • 23 April 2007
  • 1 comment

Comments

Brian

said on 25 June 2008

This worked great. Best I have found so far.

Add a comment





OKCOOL Wordpress theme created by OKCOOL