BIOS,Windows, Linux, Software,Security, Domains, Web Hosting

Auto-Resize Image Using Javascript

It is easy to resize an image using Javascript, the only thing we need to do is adding a onload even function in the image codes. This post will introduce a sample from my website. The width and height are set in the image position.

function resizeimg(obj,maxW,maxH)
{
         var imgW=obj.width;
         var imgH=obj.height;
         if(imgW>maxW||imgH>maxH)
         {       
                  var ratioA=imgW/maxW;
                  var ratioB=imgH/maxH;               
                  if(ratioA>ratioB)
                  {
                           imgW=maxW;
                           imgH=maxW*(imgH/imgW);
                  }
                  else
                  {
                           imgH=maxH;
                           imgW=maxH*(imgW/imgH);
                  }  
                  obj.width=imgW;
                  obj.height=imgH;
         }
}

Usage:

<img src="http://www.example.com/logo.gif" onload="resizeimg(this,600,1024);"/>

Normally, we need to limit the image width mainly. so I set the image height to a bigger value. If you want the image to align center. Some deep job should be done.

IMAGE BOX:

<div id="imgbox" style="width:800px;height:800px;border:1px solid #CCCCCC">
        <img src="..." onload="resizeimg(this,600,600)"/>
</div>

CSS Style:

#imgbox {text-align:center;vertical-align:middle;}
#imgbox img {vertical-align:middle;}

Or you can add some codes in Javascript (800 is a sample value):

obj.style.margin-left=(800-imgW)/2;
obj.style.margin-top=(800-imgH)/2;

Related Articles

Comments(0)  

Leave a Reply

Subscribe to BootBeta Comments RSS feed to receive notification of latest comments posted.

Subscriptions

  • Enter Email Address:

Recent Post

Copyright@ 2010-2014 Bootbeta All Rights Reserved.
HooBlog Ver 1.5 Build 20140530