Javascript Image Resize

JavascriptInternet Explorer-6Image Manipulation

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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 };
 }

Solution 4 - Javascript

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;

Solution 5 - Javascript

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.

Solution 6 - Javascript

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>

Solution 7 - Javascript

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);
		}
	}
}

Solution 8 - Javascript

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;
}

Solution 9 - Javascript

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);
}

Solution 10 - Javascript

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.

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKomangView Question on Stackoverflow
Solution 1 - JavascriptDanView Answer on Stackoverflow
Solution 2 - JavascriptKomangView Answer on Stackoverflow
Solution 3 - JavascriptJason J. NathanView Answer on Stackoverflow
Solution 4 - JavascriptNeallView Answer on Stackoverflow
Solution 5 - JavascriptPhiLhoView Answer on Stackoverflow
Solution 6 - JavascriptequimanView Answer on Stackoverflow
Solution 7 - Javascriptuser246340View Answer on Stackoverflow
Solution 8 - JavascriptDimitris DamilosView Answer on Stackoverflow
Solution 9 - JavascriptTimView Answer on Stackoverflow
Solution 10 - JavascriptvadivuView Answer on Stackoverflow
Solution 11 - JavascriptUther PendragonView Answer on Stackoverflow
Solution 12 - Javascriptuser2561474View Answer on Stackoverflow
Solution 13 - JavascriptWeijing Jay LinView Answer on Stackoverflow