IIS - resize pictures on the fly

In almost every web project, we are faced with the task of displaying various images in different sizes. It's simple - the image should be displayed in the size required by the context. If you are developing a catalog with different views, then there can be many such contexts. And it is possible that you need to make the image size adaptive to the size of the browser window (for example, Picasa Web Albums do this).

I will talk about a way to solve this problem once and for all.

What do we want


In the simplest case, we want to use the URL of the images in this form:

This should display a 100 x 100 image.

Implementation


The most direct way to solve this problem is the module for ASP.NET, which will resize the image on the fly and cache the result. I’ll note right away that naturally I’m not the first one to attend to this problem. But the solution that I propose, in my opinion, is easier to use, understand and modify.

The code


So, for everything to work, we need the module class itself and one line in Web.config.

Although the module is small, stealing a sheet of code here does not make much sense either.
Therefore, I created a gist with code . Copy this code to your project (for example, to App_Code).

Now the short settings are in yours Web.config. Add the following line to the tag or (the latter if you are using ASP.NET Devopment Server):

All is ready.

Use


As you might have guessed, you can change to the desired size any image on your site by simply adding @ widthxheight to the end of the image address.

But there are a few other modifiers that will help in different situations. You can add the following modifier letters to the end of the URL:

  • s - the module will not enlarge the picture if it is smaller than the required size.
  • c - the module will make sure that the size of the resulting image is strictly of the required size - if necessary, it will add white fields horizontally or vertically.
  • p - the module will return PNG instead of JPEG.

For example, like this: /img/aspnet.png@150x100sc.

Fine tuning and modification


You can configure the server and client caching time, the directory for storing temporary files and the compression ratio for the resulting pictures in the class header.

The module code is linear and easy to modify. For example, for security, you can specify a limited list of possible values ​​for resize options. Or complicate client caching settings (which in itself is always a big space for creativity).

Have a nice use.

Also popular now: