Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / IIS

ASP.NET VwdCms.ImageZoom Control - JavaScript to Resize/Scale Images

4.62/5 (8 votes)
24 May 2007CPOL4 min read 1   1.2K  
VwdCms.ImageZoom is a server control that provides zoom in and out and best-fit image resizing. The control is very simple and is a good example of how to manipulate the size of images with JavaScript

Try out the VwdCms.ImageZoom control online: ImageZoom Control Online Demo

Screenshot - VwdCmsImageZoom1.gif

Introduction

Level: Beginner JavaScript & DHTML

I actually built the VwdCms.ImageZoom control just as a sample control to use to test another project that I am working on - creating Toolbars and specifically sharing Toolbars between multiple controls on a page. This version of the ImageZoom does not have its own toolbar built into it - the toolbar that you see is just HTML on the sample Web Form.

I will be posting another article shortly on Toolbars which will contain a modified (enhanced) version of the VwdCms.ImageZoom as an implementation example. Rather than discussing the ImageZoom in that article, or not discussing it at all, I have decided to present it here first. I think that the JavaScript code in this control is interesting because of its simplicity. I hope that the code samples and discussion will be useful for anyone trying to manipulate or resize images / img elements on the client.

Using the Control

To add the VwdCms.ImageZoom control to your project, just follow these steps:

Step 1

Copy these files into your project directory:

  1. /App_Code/ImageZoom.cs
  2. images/zoomin.gif
  3. images/zoomout.gif
  4. images/actualsize.gif
  5. images/bestfit.gif

Step 2

Update your web.config file's Controls section: (inside the system.web section)

XML
<pages>
    <controls>
        <add tagPrefix="VwdCms" namespace="VwdCms"/>
    </controls>
</pages>

Step 3

Add a VwdCms.ImageZoom control to your Web Form:

ASP.NET
<VwdCms:ImageZoom runat="server" ID="izImgZoom"
ImageUrl="images/horizontal.jpg"
style="width:450px;height:400px;overflow:auto;" />

Step 4

Create a toolbar similar to the one in the sample project. Note: I will be posting an updated version of the VwdCms.ImageZoom control soon that has a built-in Toolbar and will support "Toolbar Sharing".

All of the JavaScript code is included in the C# class so there is no need to include a script reference. The element IDs that appear in the code sample below are automatically generated by the C# class, so you do not need to worry about setting them or hard-coding them.

I have verified that this code works in Internet Explorer 7 and Firefox 2.0.

Key Concepts

When you want to modify the dimensions of an image that will be rendered on a Web page, the key to making them look good is to only set one of the dimensions. By setting the width only, you are allowing the browser to scale the image and determine the height - the result is a much more presentable looking enlargement or reduction.

The same holds true for zooming in or out on images using JavaScript - just set one dimension, I prefer to set the width property. Another key point in zooming in and out is getting the image to return back to its original size. You don't need to do any fancy coding or store the original width in variables, all you do is remove the width attribute from the image (img element) using the standard DOM removeAttribute('width') method. After you remove the width attribute, the browser will render the image at its original size.

The 'Best Fit' code is interesting because as it turned out, it was not really that complicated. To do a 'Best Fit' on an image, you need to know the 'aspect ratio' (ar in the code) for the image and you need to know the width (clientWidth, cw in the code) and height (clientHeight, ch in the code) of the box that you want to fit the image into.

Aspect Ratio: ar = img.width / img.height;

An aspect ratio greater than 1.0 means that the image's width is greater than its height. Alternatively, an aspect ratio less than 1.0 means that the image's height is greater than its width.

Using the information above, we need to set the width of the image for the two situations.

Aspect Ratio >= 1.0 : Set the width of the image equal to the width of the box that you want to fit it into, img.width = cw;.

Aspect Ratio < 1.0 : Compute the width of the image using width = ch * ar;, this is just a rearrangement of the Aspect Ratio formula above except that in place of the img.width, I have substituted in the 'box height' ch and the net result of the equation is a width scaled based on the height of the box I want to fit the image into.

JavaScript Code

The neat part of this control is really the JavaScript because it is so simple...

JavaScript
function setImage(src)
{
    try
    {
        var img = document.getElementById('imgMain');

        // make sure image is loaded using its
        // original dimensions the first time
        img.removeAttribute('width');

        // change the URL for the image element
        img.src = src;
    }
    catch(e)
    {
        alert('setImage error: ' + e.message);
    }
}

function zoomIn()
{
    try
    {
        var img = document.getElementById('imgMain');

        // zoom in by 25%
        img.width = img.width * 1.25;
    }
    catch(e)
    {
        alert('zoomIn error: ' + e.message);
    }
}

function zoomOut()
{
    try
    {
        var img = document.getElementById('imgMain');

        // zoom out by 25%
        img.width = img.width * 0.75;
    }
    catch(e)
    {
        alert('zoomOut error: ' + e.message);
    }
}

function actualSize()
{
    try
    {
        var img = document.getElementById('imgMain');

        // return the image back to its
        // original dimensions
        img.removeAttribute('width');
    }
    catch(e)
    {
        alert('actualSize error: ' + e.message);
    }
}

function bestFit()
{
    try
    {
        var iz = document.getElementById('izImgZoom');
        var img = document.getElementById('imgMain');
        var cw = iz.clientWidth;

        // sometimes the clientWidth is 0 in IE,
        // so look at the parent elements until
        // a valid clientWidth is found
        while ( cw == 0 )
        {
            iz = iz.parentElement;
            cw = iz.clientWidth;
        }
        var ch = iz.clientHeight;

        // return the image back to its
        // original dimensions
        img.removeAttribute('width');

        // calculate the aspect ratio
        var ar = img.width / img.height;

        if ( ar >= 1.0 )
        {
            // easy, set the image width to
            // the 'box width' minus 2 pixes for
            // the border of the image
            img.width = cw-2;
        }
        else
        {
            // compute the image width using
            // the 'box height' and 'aspect ratio'
            // minus 2 pixes for the border of the image
            img.width = Math.floor(ch * ar)-2;
        }
    }
    catch(e)
    {
        alert('bestFit error: ' + e.message);
    }
}

History

  • 24th May, 2007 - Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)