Kilone.com





Dynamic Image Resizing at runtime using c#

by Omar AlBadri on 9/24/2009 3:56:00 PM

Read about Dynamic Image Resizing

Dynamic Image Resizing using C#

Images play a huge part in the look and feel of a web site. Trouble is that as design gets more and more complex and web 2.0-y image sizing and their proportions play a big part in the design.

In many dynamic sites and user generated content sites, displaying these images with correct proportion is key to the look and feel of the site. What do you do when you are given images of various width and heights and are suppose to make sure they fit inside a fixed width/height div?

You can do three things:

  1. 1. Css resize them: The problem with this is that they will be stretching and skewing of the images
  2. 2. Have the image uploader resize the images - great idea but will cost you for a uploader plus your users also have to know what they are doing
  3. 3. Resize the file on save - works great but what happens when your dealing with legacy images?
  4. 4. Resize the images dynamically in runtime: best option for now

Image resizing is a tricky subject you have to deal with image distortion, aspect ration, etc. etc. What I am trying to do here is provide a plug in solution that you can add to your site with very little coding.

Lets think about what we want to do:

  1. 1. We need the image to resize proportionate to its aspect ration BUT we also need to squeeze into some spots
  2. 2. We might need to decode an encrypted URL
  3. 3. We need to specify a Max for both height and with and either squeeze the image into the space provided or scale to fit.

So I create a page called ImageResize.aspx that will take parameters(including path to image) and resize the image dynamically. Here how it works:

It will resize too the aspect ration IF only height or width are provided if both are provided it will rescale to the height and width provided.

MaxHeight and MaxWidth can be specified. These are used if you are scaling proportionally but have a fixed amount of space available and you want to ensure the resizing does not go over the bounds. If you set ResizeMax=true then if the image overshoots its bounds on the resize it will space back down to the Max's specified.

A background color can be specified for round PNG's .

Encrypted URLS can be used

Take a look at the test page here

You can download the project here

Try it out and provide comments.

 

Post your comment

Thanks for your comments

Be nice ;)

  • Comment