A critical vulnerability was discovered in React Server Components (Next.js). Our systems remain protected but we advise to update packages to newest version. Learn More

Anders Hattestad
Aug 14, 2012
  10925
(0 votes)

Automatically change images in a responsive design to scale

A lot of new sites uses responsive design. The key feature with this of course that the web page scale to the current view port of the device a user is using.  Images and other elements are often set to width:100% in the css. The problem that we then have to solve is to return to the user a images that is in the correct size in pixels.

I have wrote a concept around this based on the current alloy template site.

First of all I want to change all images that are returned from a request. I wrote my self a module ChangeImageSource  that I can add in the master page like this.

MasterPage.master
<asp:ContentPlaceHolder ID="MainContentRegion" runat="server">
    <div id="MainBodyArea">
        <Itera:ChangeImageSource runat="server" ID="ChangeImageArea">
            <asp:ContentPlaceHolder ID="MainBodyRegion" runat="server">
                <div id="MainBody">
                    <AlloyTech:MainBody runat="server" />
                </div>
            </asp:ContentPlaceHolder>
        </Itera:ChangeImageSource>
    </div>
    <div id="SecondaryBodyArea">
        <Itera:ChangeImageSource runat="server" ID="ChangeImageSource1" AddBox="border">
            <asp:ContentPlaceHolder ID="SecondaryBodyRegion" runat="server">
                <div id="SecondaryBody">
                    <EPiServer:Property PropertyName="SecondaryBody" EnableViewState="false" runat="server" />
                </div>
            </asp:ContentPlaceHolder>
        </Itera:ChangeImageSource>
    </div>
</asp:ContentPlaceHolder>

This module replace every images inside its content with a reference to a empty images, and add the original image in a new attribute called orgsrc.

<img orgsrc="/PageFiles/5/Desert.jpg" alt="" 
src="/Itera.ResponsiveResize/ZeroSize.png" class="scaleImage">

The code that replace all images in a given tag is done like this using HtmlAgilityPack

protected override void Render(HtmlTextWriter writer)
{
    if (this.Page.Request["dontChangeImages"] == null)
    {
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        base.Render(htw);

        string content = sb.ToString();
        //writer.Write("content length=" + content.Length);
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(content);
        var images = doc.DocumentNode.SelectNodes("//img[@src]");
        if (images != null)
        {
            foreach (HtmlNode image in images)
            {
                HtmlAttribute src = image.Attributes["src"];

                image.Attributes.Add("orgsrc", src.Value);
                src.Value = "/Itera.ResponsiveResize/ZeroSize.png";
                if (image.Attributes["width"] != null)
                {
                    image.Attributes.Remove("width");
                }
                if (image.Attributes["height"] != null)
                {
                    image.Attributes.Remove("height");
                }
                if (image.Attributes["class"] == null)
                {
                    image.Attributes.Add("class", AddClass);
                }
                else
                {
                    image.Attributes["class"].Value = image.Attributes["class"].Value + " scaleImage";
                }
                if (!string.IsNullOrEmpty(AddBox))
                {
                    var newNode = HtmlNode.CreateNode("<div class='" + AddBox + "'>" + image.OuterHtml+ "</div>");

                    image.ParentNode.ReplaceChild(newNode, image);

                }
            }
        }
        writer.Write("<div id='" + UnikID + "'>");
        writer.Write(doc.DocumentNode.OuterHtml);
        writer.Write("</div>");
        writer.Write("<div id='Log" + UnikID + "'></div>");
               
    }
    else
    {
        base.Render(writer);
    }
}

Then the module add some JavaScript that after the page is loaded find all images in the current zone and uses JQuery to find the current width in pixels and change the image source to a reference to a scaled images with the correct width. And if the pages is resized it will change the images. To save some cpu, it will use a images that is round up to the next hundred. The actually resizing of the pictures can be done with a lot of different te4chinces , but this demo uses ImageResizer

$(document).ready(function () {
    $('#133d8cb8fb224834bbfdde298adbec25 img').each(function (i) {

        if (!$(this).attr('orgsrc')) {
            var img = $(this).attr('src');
            $(this).attr('orgsrc', img);
        }
        ResizeImageWith100Procent133d8cb8fb224834bbfdde298adbec25($(this));
    });
});

$(window).resize(function () {
    $('#log133d8cb8fb224834bbfdde298adbec25').append('<div>resize finished</div>');
    $('#133d8cb8fb224834bbfdde298adbec25 img').each(function (i) {
        if ($(this).attr('orgsrc')) {
            ResizeImageWith100Procent133d8cb8fb224834bbfdde298adbec25($(this));
        }
    });

});
function ResizeImageWith100Procent133d8cb8fb224834bbfdde298adbec25(obj)
{
    var orgsrc = obj.attr('orgsrc');
    var width = obj.width();

            width /= 100;
            width = Math.ceil(width);
            width *= 100;
            if (obj.attr('src').indexOf('width_' + width) == -1) {
                obj.attr('src',  orgsrc + '?width=' + width );
               
            }
}
image
<img orgsrc="/PageFiles/5/Desert.jpg" alt=""
src="/PageFiles/5/Desert.jpg?width=500" class="half100Procent scaleImage"> <img orgsrc="/PageFiles/5/product3Prev.png" alt="prevproduct1"
src="/PageFiles/5/product3Prev.png?width=200" class="border scaleImage">
image
image
<img orgsrc="/PageFiles/5/Desert.jpg" alt=""
src="/PageFiles/5/Desert.jpg?width=400" class="border scaleImage">
image
<img orgsrc="/PageFiles/5/product3Prev.png" alt="prevproduct1"
src="/PageFiles/5/product3Prev.png?width=400" class="border scaleImage">

What you need to do is to unzip the file and add the dll’s from the project to your bin folder, and

change the web.config to use ImageResizer.

Then you need to add the web control in the master page

 

Have added a working web.config and a working master.page from the

alloy project along with the zip of the project

Download here

Aug 14, 2012

Comments

Please login to comment.
Latest blogs
A day in the life of an Optimizely OMVP: Learning Optimizely Just Got Easier: Introducing the Optimizely Learning Centre

On the back of my last post about the Opti Graph Learning Centre, I am now happy to announce a revamped interactive learning platform that makes...

Graham Carr | Jan 31, 2026

Scheduled job for deleting content types and all related content

In my previous blog post which was about getting an overview of your sites content https://world.optimizely.com/blogs/Per-Nergard/Dates/2026/1/sche...

Per Nergård (MVP) | Jan 30, 2026

Working With Applications in Optimizely CMS 13

💡 Note:  The following content has been written based on Optimizely CMS 13 Preview 2 and may not accurately reflect the final release version. As...

Mark Stott | Jan 30, 2026

Experimentation at Speed Using Optimizely Opal and Web Experimentation

If you are working in experimentation, you will know that speed matters. The quicker you can go from idea to implementation, the faster you can...

Minesh Shah (Netcel) | Jan 30, 2026

How to run Optimizely CMS on VS Code Dev Containers

VS Code Dev Containers is an extension that allows you to use a Docker container as a full-featured development environment. Instead of installing...

Daniel Halse | Jan 30, 2026

A day in the life of an Optimizely OMVP: Introducing Optimizely Graph Learning Centre Beta: Master GraphQL for Content Delivery

GraphQL is transforming how developers query and deliver content from Optimizely CMS. But let's be honest—there's a learning curve. Between...

Graham Carr | Jan 30, 2026