[javascript] Javascript Image Resize

Does anyone know how to resize images proportionally using JavaScript?

I have tried to modify the DOM by adding attributes height and width on the fly, but seems did not work on IE6.

This question is related to javascript internet-explorer-6 image-manipulation

The answer is


okay it solved, here is my final code

if($(this).width() > $(this).height()) { 
 $(this).css('width',MaxPreviewDimension+'px');
 $(this).css('height','auto');
} else {
 $(this).css('height',MaxPreviewDimension+'px');
 $(this).css('width','auto');
}

Thanks guys


I have answered this question here: How to resize images proportionally / keeping the aspect ratio?. I am copying it here because I really think it is a very reliable method :)

 /**
  * Conserve aspect ratio of the original region. Useful when shrinking/enlarging
  * images to fit into a certain area.
  *
  * @param {Number} srcWidth width of source image
  * @param {Number} srcHeight height of source image
  * @param {Number} maxWidth maximum available width
  * @param {Number} maxHeight maximum available height
  * @return {Object} { width, height }
  */
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {

    var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);

    return { width: srcWidth*ratio, height: srcHeight*ratio };
 }

Tried the following code, worked OK on IE6 on WinXP Pro SP3.

function Resize(imgId)
{
  var img = document.getElementById(imgId);
  var w = img.width, h = img.height;
  w /= 2; h /= 2;
  img.width = w; img.height = h;
}

Also OK in FF3 and Opera 9.26.


Instead of modifying the height and width attributes of the image, try modifying the CSS height and width.

myimg = document.getElementById('myimg');
myimg.style.height = "50px";
myimg.style.width = "50px";

One common "gotcha" is that the height and width styles are strings that include a unit, like "px" in the example above.

Edit - I think that setting the height and width directly instead of using style.height and style.width should work. It would also have the advantage of already having the original dimensions. Can you post a bit of your code? Are you sure you're in standards mode instead of quirks mode?

This should work:

myimg = document.getElementById('myimg');
myimg.height = myimg.height * 2;
myimg.width = myimg.width * 2;

This works for all cases.

function resizeImg(imgId) {
    var img = document.getElementById(imgId);
    var $img = $(img);
    var maxWidth = 110;
    var maxHeight = 100;
    var width = img.width;
    var height = img.height;
    var aspectW = width / maxWidth;
    var aspectH = height / maxHeight;

    if (aspectW > 1 || aspectH > 1) {
        if (aspectW > aspectH) {
            $img.width(maxWidth);
            $img.height(height / aspectW);
        }
        else {
            $img.height(maxHeight);
            $img.width(width / aspectH);
        }
    }
}

okay it solved, here is my final code

if($(this).width() > $(this).height()) { 
 $(this).css('width',MaxPreviewDimension+'px');
 $(this).css('height','auto');
} else {
 $(this).css('height',MaxPreviewDimension+'px');
 $(this).css('width','auto');
}

Thanks guys


Instead of modifying the height and width attributes of the image, try modifying the CSS height and width.

myimg = document.getElementById('myimg');
myimg.style.height = "50px";
myimg.style.width = "50px";

One common "gotcha" is that the height and width styles are strings that include a unit, like "px" in the example above.

Edit - I think that setting the height and width directly instead of using style.height and style.width should work. It would also have the advantage of already having the original dimensions. Can you post a bit of your code? Are you sure you're in standards mode instead of quirks mode?

This should work:

myimg = document.getElementById('myimg');
myimg.height = myimg.height * 2;
myimg.width = myimg.width * 2;

Use JQuery

var scale=0.5;

minWidth=50;
minHeight=100;

if($("#id img").width()*scale>minWidth && $("#id img").height()*scale >minHeight)
{
    $("#id img").width($("#id img").width()*scale);
    $("#id img").height($("#id img").height()*scale);
}

okay it solved, here is my final code

if($(this).width() > $(this).height()) { 
 $(this).css('width',MaxPreviewDimension+'px');
 $(this).css('height','auto');
} else {
 $(this).css('height',MaxPreviewDimension+'px');
 $(this).css('width','auto');
}

Thanks guys


You don't have to do it with Javascript. You can just create a CSS class and apply it to your tag.

.preview_image{
        width: 300px;
    height: auto;
    border: 0px;
}

Instead of modifying the height and width attributes of the image, try modifying the CSS height and width.

myimg = document.getElementById('myimg');
myimg.style.height = "50px";
myimg.style.width = "50px";

One common "gotcha" is that the height and width styles are strings that include a unit, like "px" in the example above.

Edit - I think that setting the height and width directly instead of using style.height and style.width should work. It would also have the advantage of already having the original dimensions. Can you post a bit of your code? Are you sure you're in standards mode instead of quirks mode?

This should work:

myimg = document.getElementById('myimg');
myimg.height = myimg.height * 2;
myimg.width = myimg.width * 2;

function resize_image(image, w, h) {

    if (typeof(image) != 'object') image = document.getElementById(image);

    if (w == null || w == undefined)
        w = (h / image.clientHeight) * image.clientWidth;

    if (h == null || h == undefined)
        h = (w / image.clientWidth) * image.clientHeight;

    image.style['height'] = h + 'px';
    image.style['width'] = w + 'px';
    return;
}

just pass it either an img DOM element, or the id of an image element, and the new width and height.

or you can pass it either just the width or just the height (if just the height, then pass the width as null or undefined) and it will resize keeping aspect ratio


Here is my cover fill solution (similar to background-size: cover, but it supports old IE browser)

<div class="imgContainer" style="height:100px; width:500px; overflow:hidden; background-color: black">
    <img src="http://dev.isaacsonwebdevelopment.com/sites/development/files/views-slideshow-settings-jquery-cycle-custom-options-message.png" id="imgCat">
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
<script>
    $(window).load(function() {
        var heightRate =$("#imgCat").height() / $("#imgCat").parent(".imgContainer").height();
        var widthRate = $("#imgCat").width() / $("#imgCat").parent(".imgContainer").width();

        if (window.console) {
            console.log($("#imgCat").height());
            console.log(heightRate);
            console.log(widthRate);
            console.log(heightRate > widthRate);
        }
        if (heightRate <= widthRate) {
            $("#imgCat").height($("#imgCat").parent(".imgContainer").height());
        } else {
            $("#imgCat").width($("#imgCat").parent(".imgContainer").width());
        }
    });
</script>

Tried the following code, worked OK on IE6 on WinXP Pro SP3.

function Resize(imgId)
{
  var img = document.getElementById(imgId);
  var w = img.width, h = img.height;
  w /= 2; h /= 2;
  img.width = w; img.height = h;
}

Also OK in FF3 and Opera 9.26.


Try this..

<html>
<body>
<head>
<script type="text/javascript">
function splitString()
{
var myDimen=document.getElementById("dimen").value;
var splitDimen = myDimen.split("*");
document.getElementById("myImage").width=splitDimen[0];
document.getElementById("myImage").height=splitDimen[1];
}
</script>
</head>

<h2>Norwegian Mountain Trip</h2>
<img border="0" id="myImage" src="..." alt="Pulpit rock" width="304" height="228" /><br>
<input type="text" id="dimen" name="dimension" />
<input type="submit" value="Submit" Onclick ="splitString()"/>

</body>
</html>

In the text box give the dimension as ur wish, in the format 50*60. Click submit. You will get the resized image. Give your image path in place of dots in the image tag.


This works for all cases.

function resizeImg(imgId) {
    var img = document.getElementById(imgId);
    var $img = $(img);
    var maxWidth = 110;
    var maxHeight = 100;
    var width = img.width;
    var height = img.height;
    var aspectW = width / maxWidth;
    var aspectH = height / maxHeight;

    if (aspectW > 1 || aspectH > 1) {
        if (aspectW > aspectH) {
            $img.width(maxWidth);
            $img.height(height / aspectW);
        }
        else {
            $img.height(maxHeight);
            $img.width(width / aspectH);
        }
    }
}

Example: How To resize with a percent

<head>
    <script type="text/javascript">
        var CreateNewImage = function (url, value) {
            var img = new Image;
            img.src = url;
            img.width = img.width * (1 + (value / 100));
            img.height = img.height * (1 + (value / 100));

            var container = document.getElementById ("container");
            container.appendChild (img);
        }
    </script>
</head>
<body>
    <button onclick="CreateNewImage ('http://www.medellin.gov.co/transito/images_jq/imagen5.jpg', 40);">Zoom +40%</button>
    <button onclick="CreateNewImage ('http://www.medellin.gov.co/transito/images_jq/imagen5.jpg', 60);">Zoom +50%</button>
    <div id="container"></div>
</body>

function resize_image(image, w, h) {

    if (typeof(image) != 'object') image = document.getElementById(image);

    if (w == null || w == undefined)
        w = (h / image.clientHeight) * image.clientWidth;

    if (h == null || h == undefined)
        h = (w / image.clientWidth) * image.clientHeight;

    image.style['height'] = h + 'px';
    image.style['width'] = w + 'px';
    return;
}

just pass it either an img DOM element, or the id of an image element, and the new width and height.

or you can pass it either just the width or just the height (if just the height, then pass the width as null or undefined) and it will resize keeping aspect ratio


You don't have to do it with Javascript. You can just create a CSS class and apply it to your tag.

.preview_image{
        width: 300px;
    height: auto;
    border: 0px;
}

to resize image in javascript:

$(window).load(function() {
mitad();doble();
});
function mitad(){ 

    imag0.width=imag0.width/2;
    imag0.height=imag0.height/2;

    }
function doble(){ 
  imag0.width=imag0.width*2; 
  imag0.height=imag0.height*2;}

imag0 is the name of the image:

 <img src="xxx.jpg" name="imag0">

Example: How To resize with a percent

<head>
    <script type="text/javascript">
        var CreateNewImage = function (url, value) {
            var img = new Image;
            img.src = url;
            img.width = img.width * (1 + (value / 100));
            img.height = img.height * (1 + (value / 100));

            var container = document.getElementById ("container");
            container.appendChild (img);
        }
    </script>
</head>
<body>
    <button onclick="CreateNewImage ('http://www.medellin.gov.co/transito/images_jq/imagen5.jpg', 40);">Zoom +40%</button>
    <button onclick="CreateNewImage ('http://www.medellin.gov.co/transito/images_jq/imagen5.jpg', 60);">Zoom +50%</button>
    <div id="container"></div>
</body>

Here is my cover fill solution (similar to background-size: cover, but it supports old IE browser)

<div class="imgContainer" style="height:100px; width:500px; overflow:hidden; background-color: black">
    <img src="http://dev.isaacsonwebdevelopment.com/sites/development/files/views-slideshow-settings-jquery-cycle-custom-options-message.png" id="imgCat">
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
<script>
    $(window).load(function() {
        var heightRate =$("#imgCat").height() / $("#imgCat").parent(".imgContainer").height();
        var widthRate = $("#imgCat").width() / $("#imgCat").parent(".imgContainer").width();

        if (window.console) {
            console.log($("#imgCat").height());
            console.log(heightRate);
            console.log(widthRate);
            console.log(heightRate > widthRate);
        }
        if (heightRate <= widthRate) {
            $("#imgCat").height($("#imgCat").parent(".imgContainer").height());
        } else {
            $("#imgCat").width($("#imgCat").parent(".imgContainer").width());
        }
    });
</script>

Tried the following code, worked OK on IE6 on WinXP Pro SP3.

function Resize(imgId)
{
  var img = document.getElementById(imgId);
  var w = img.width, h = img.height;
  w /= 2; h /= 2;
  img.width = w; img.height = h;
}

Also OK in FF3 and Opera 9.26.


to resize image in javascript:

$(window).load(function() {
mitad();doble();
});
function mitad(){ 

    imag0.width=imag0.width/2;
    imag0.height=imag0.height/2;

    }
function doble(){ 
  imag0.width=imag0.width*2; 
  imag0.height=imag0.height*2;}

imag0 is the name of the image:

 <img src="xxx.jpg" name="imag0">

Try this..

<html>
<body>
<head>
<script type="text/javascript">
function splitString()
{
var myDimen=document.getElementById("dimen").value;
var splitDimen = myDimen.split("*");
document.getElementById("myImage").width=splitDimen[0];
document.getElementById("myImage").height=splitDimen[1];
}
</script>
</head>

<h2>Norwegian Mountain Trip</h2>
<img border="0" id="myImage" src="..." alt="Pulpit rock" width="304" height="228" /><br>
<input type="text" id="dimen" name="dimension" />
<input type="submit" value="Submit" Onclick ="splitString()"/>

</body>
</html>

In the text box give the dimension as ur wish, in the format 50*60. Click submit. You will get the resized image. Give your image path in place of dots in the image tag.


Use JQuery

var scale=0.5;

minWidth=50;
minHeight=100;

if($("#id img").width()*scale>minWidth && $("#id img").height()*scale >minHeight)
{
    $("#id img").width($("#id img").width()*scale);
    $("#id img").height($("#id img").height()*scale);
}

I have answered this question here: How to resize images proportionally / keeping the aspect ratio?. I am copying it here because I really think it is a very reliable method :)

 /**
  * Conserve aspect ratio of the original region. Useful when shrinking/enlarging
  * images to fit into a certain area.
  *
  * @param {Number} srcWidth width of source image
  * @param {Number} srcHeight height of source image
  * @param {Number} maxWidth maximum available width
  * @param {Number} maxHeight maximum available height
  * @return {Object} { width, height }
  */
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {

    var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);

    return { width: srcWidth*ratio, height: srcHeight*ratio };
 }

Tried the following code, worked OK on IE6 on WinXP Pro SP3.

function Resize(imgId)
{
  var img = document.getElementById(imgId);
  var w = img.width, h = img.height;
  w /= 2; h /= 2;
  img.width = w; img.height = h;
}

Also OK in FF3 and Opera 9.26.


okay it solved, here is my final code

if($(this).width() > $(this).height()) { 
 $(this).css('width',MaxPreviewDimension+'px');
 $(this).css('height','auto');
} else {
 $(this).css('height',MaxPreviewDimension+'px');
 $(this).css('width','auto');
}

Thanks guys