πŸ“œ ⬆️ ⬇️

IIS - resize images on the fly

In almost every web project, we are faced with the task of displaying certain images in different sizes. Everything is simple - the image should be displayed in the size required by the context. If you develop a directory with different views, then there may be many such contexts. And it may be necessary to make the size of the image adaptive in relation to the size of the browser window (for example, Picasa Web Albums does this).

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

What we want


In the simplest case, we want to use image URLs like this:
< img src = ” / img / photo.jpg@100x100” / >

This should display a 100 x 100 picture.
')

Implementation


The most direct way to solve this problem is a module for ASP.NET, which will resize the image on the fly and cache the result. Immediately, I note that of course I am not the first to attend to this problem. But the solution that I propose is, in my opinion, easier to use, understand, and modify.

Code


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

Although the module is not large, there is no sense to steal a sheet of code from here either.
Therefore, I created gist c code . Copy this code to your project (for example, in App_Code ).

Now the short settings in your Web.config . Add the <httpModules> <modules> to the <modules> or <httpModules> (the latter, if you are using ASP.NET Devopment Server):
<add name = "ImageResizeModule" type = "GarageTools.ImageResizeModule" />

All is ready.

We use


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

But there are a few modifiers that will help in different situations. At the end of the URL, you can add the following modifier letters:


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

Tweaks and Modifications


You can configure server and client caching time, temporary files storage directory and compression ratio for the resulting images 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 parameters. Or complicate client caching settings (which in itself is always a big space for creativity).

Enjoy using.

Source: https://habr.com/ru/post/160059/


All Articles