Search code examples
c#asp.net-mvcimageresizerretina.jsimageresizer-diskcache

Automatically serving @2x and @3x images using ImageResizer on MVC


Theme that we are building our websties utilizes Retina.Js on the frontend, which automatically tries to load @2x and @3x images according to users device in such way that;

If we are serving our sliders for the desktop using image resizer as follows;

/Images/home/slides/slide-1.jpg?width=300

(in which 1 is the DbId of the image)

This script automatically request the following images if the visitor is using high dpi mobile device;

/Images/home/slides/[email protected]?width=300

/Images/home/slides/[email protected]?width=300

We are using ImageResizer with SqlReader and DiskCache Plugins, so that the images read from database and cached on the disk.

When the script requests @2x and @3x naming convetion images from server, of course ImageResizer returned error for those images since it could not find an image with id '1@2x' in the db, but fortunately we were able to overcome this obstacle by using Pipeline.Rewrite;

ImageResizer.Configuration.Config.Current.Pipeline.Rewrite += delegate (IHttpModule s, HttpContext context, ImageResizer.Configuration.IUrlEventArgs ev)
        {

            if (ev.VirtualPath.StartsWith(VirtualPathUtility.ToAbsolute("~/kitimages/"), StringComparison.OrdinalIgnoreCase))
            {
                if (ev.VirtualPath.Contains("@2x"))
                {
                    ev.VirtualPath = ev.VirtualPath.Replace("@2x", string.Empty);
                }

            }                

        };

so that now we are able serve the images which are @2x (or@3x in that manner) on the desktop resolution.

But what we could not achieve that change resolution of the desires @2x or @3x image. Since we are calling image '?width=300' with querystring parameter these images also served as desktop resolution.

We tried to change

ImageResizer.Configuration.Config.Current.Pipeline.ModifiedQueryString["width"] 

to newly calculated value which had no effect.

Set new value to width under

context.Items["resizer.modifiedQueryString"] 

property which had no effect.

Also tried to use the following with no luck;

ImageResizer.Configuration.Config.Current.Pipeline.Modify( new ResizeSettings() { Width = 600 } );
ImageResizer.Configuration.Config.Current.CurrentImageBuilder.SettingsModifier.Modify(new ResizeSettings() {Width = 600});
ImageResizer.Configuration.Config.Current.Pipeline.GetImageBuilder().SettingsModifier.Modify(new ResizeSettings() { Width = 600 });

Now the question is; is there any way to change the resize settings on the fly while using SqlReader and DiskCache plugins and serve @2x and @3x images with the correct resolutions?

Thanks in advance,


Solution

  • ImageResizer offers a zoom parameter that does the math for you, essentially multiplying the width and height paramters.

    ev.QueryString["zoom"] = 2; // 3, etc,