Does anyone know how to resize images proportionally using JavaScript?
I have tried to modify the DOM by adding attributes height
and width
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 };
}
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);
}
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
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>
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">