50

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.

Adriano
  • 3,788
  • 5
  • 32
  • 53
Komang
  • 5,004
  • 4
  • 29
  • 33
  • 7
    For those looking for resizing before upload: http://stackoverflow.com/questions/2434458/image-resizing-client-side-with-javascript-before-upload-to-the-server – mikemaccana Apr 02 '13 at 09:23
  • I simply resize one of the dimensions, and the other dimension is automagically changed proportionally :) – Mitch Match Nov 09 '15 at 07:25

13 Answers13

71

To modify an image proportionally, simply only alter one of the width/height css properties, leave the other set to auto.

image.style.width = '50%'
image.style.height = 'auto'

This will ensure that its aspect ratio remains the same.

Bear in mind that browsers tend to suck at resizing images nicely - you'll probably find that your resized image looks horrible.

Dan
  • 61,568
  • 9
  • 61
  • 78
19

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

Komang
  • 5,004
  • 4
  • 29
  • 33
  • Incidentally, unless you have set a height on the image (either the `height` attribute, or via CSS), you don't need to explicitly set `height: auto` - it's set to that by default – Dan Oct 04 '08 at 17:24
  • no when i resize the width without setting the height to auto it failed in IE6 – Komang Oct 04 '08 at 18:28
  • Odd, I'm sure I've done that before and have it work. Anyway, I'll take your word for it :) You could apply that height:auto in a stylesheet, though – Dan Oct 05 '08 at 00:03
  • I tried it on IE6 Win XP SP3, image 297px x 169px and resize the width to 100px but the height remain its original, but its probably Jquery add it automatically, i'll try to find out. – Komang Oct 05 '08 at 04:29
  • 1
    My understanding is that in jQuery, $() is a class constructor. That means that this code will always instantiate four wrappers for "this" when a single one would do if you stored it in a variable. I might even be tempted to store $(this) in a class-level variable in your constructor. – Joel Mueller Oct 05 '08 at 20:51
  • joel you are right, but these block codes is a part of looping so $(this) here refer to the image itself as an object – Komang Oct 08 '08 at 07:04
  • 2
    `var target = $(this); if (target.width() > target.height()) target.css({ "width": MaxPreviewDimension + "px", "height": "auto" }); else target.css({ "height": MaxPreviewDimension + "px", "width": auto })` – Oybek Feb 28 '12 at 09:22
9

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 };
 }
Pang
  • 9,564
  • 146
  • 81
  • 122
Jason J. Nathan
  • 7,422
  • 2
  • 26
  • 37
6

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;
Neall
  • 26,428
  • 5
  • 49
  • 48
4

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.

PhiLho
  • 40,535
  • 6
  • 96
  • 134
3

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>
equiman
  • 7,810
  • 2
  • 45
  • 47
3

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);
        }
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
user246340
  • 45
  • 1
  • 7
2

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;
}
Dimitris Damilos
  • 2,363
  • 5
  • 23
  • 46
1

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);
}
julx
  • 8,694
  • 6
  • 47
  • 86
Tim
  • 11
  • 1
1

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.

vadivu
  • 11
  • 2
0
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

0

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">
  • Thank you, this is the code that I could understand and use. One weird thing I found is that changing the width was the only thing I needed to do in order to scale the image down (if I were then to change the height, it would actually flatten/skew the image). – user2616155 Aug 01 '19 at 13:50
0

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>
Weijing Jay Lin
  • 2,991
  • 6
  • 33
  • 53