Click here to Skip to main content
Click here to Skip to main content

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

, 24 May 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
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)

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

Step 3

Add a VwdCms.ImageZoom control to your Web Form:

    <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...

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)

Share

About the Author

Jeff Bazinet
Web Developer
United States United States
VWD-CMS is an ASP.NET content management system designed and developed by Jeff Bazinet.

While VWD-CMS has been developed entirely in Visual Web Developer, it will power any ASP.NET 2.0 website.

VWD-CMS is a file based content management system that has been built with developers in mind -

one of the primary design requirements is that the CMS does not constrain or limit a developer.

Try the online demo and learn more about VWD-CMS at www.vwd-cms.com

Comments and Discussions

 
GeneralGreat work indeed! PinmemberJigneshhrathod24-May-12 3:46 
GeneralMy vote of 5 Pinmembermanoj kumar choubey16-Feb-12 1:23 
GeneralProblem with the demo code Pinmemberweberdavid22-Oct-10 0:13 
GeneralHelp about width of object PinmemberF2F8-Sep-07 18:50 
GeneralSmall improvement Pinmembertfranch30-Aug-07 2:17 
Question??? Pinmembermerlin98124-May-07 7:59 
AnswerRe: ??? PinmemberVWD-CMS24-May-07 8:45 
GeneralExcellent Pinmembermerlin98124-May-07 4:08 
AnswerRe: Excellent PinsitebuilderUwe Keim24-May-07 5:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 24 May 2007
Article Copyright 2007 by Jeff Bazinet
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid