2008-10-04 13 views
40

¿Alguien sabe cómo cambiar el tamaño de la imagen proporcionalmente usando JavaScript? He intentado modificar los atributos de adición de DOM altura & sobre la marcha, pero parece que no funcionó en IE6.Javascript Image Resize

+7

Para aquellos que buscan cambiar el tamaño antes de subir: http: // sta ckoverflow.com/questions/2434458/image-resizing-client-side-with-javascript-before-upload-to-the-server – mikemaccana

+0

Simplemente cambio el tamaño de una de las dimensiones, y la otra dimensión se cambia automágicamente proporcionalmente :) –

Respuesta

62

Para modificar una imagen proporcionalmente, simplemente solamente alterar una de las propiedades css anchura/altura, dejar el otro en AUTO.

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

Esto asegurará que su relación de aspecto permanezca igual.

Tenga en cuenta que los navegadores tienden a chupar al cambiar el tamaño de las imágenes muy bien - probablemente encontrará que su tamaño de imagen se ve horrible.

+0

tal vez agregue un texto publicitario al cambiar el tamaño de la imagen antes de cargarla en un servidor –

6

En lugar de modificar los atributos de altura y ancho de la imagen, intente modificar el alto y el ancho de CSS.

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

Una común "Gotcha" es que la altura y anchura estilos son cadenas que incluyen una unidad, como "px" en el ejemplo anterior.

Editar - Creo que el ajuste de la altura y el ancho directamente en lugar de usar style.height y style.width debería funcionar. También tendría la ventaja de tener las dimensiones originales. ¿Puedes publicar un poco de tu código? ¿Estás seguro de que estás en el modo estándar en lugar del modo peculiar?

Esto debería funcionar:

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

Probé el siguiente código, funcionó bien en IE6 en 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; 
} 

También está bien en FF3 y Opera 9.26.

18

bien se resuelve, aquí está mi código final

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

Gracias chicos

+0

Por cierto, a menos que haya establecido una altura en la imagen (ya sea el atributo 'height', o mediante CSS), no necesita establecer explícitamente' height: auto' - está configurado para eso de forma predeterminada – Dan

+0

no cuando cambio el ancho del ancho sin establecer la altura en automático, falló en IE6 – Komang

+0

Impar, estoy seguro de que ya lo he hecho antes y que funcione. De todos modos, tomaré tu palabra :) Puedes aplicar esa altura: automático en una hoja de estilo, aunque – Dan

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

sólo tiene que pasar ya sea un elemento img DOM, o el id de un elemento de imagen, y el nuevo ancho y altura

o puede pasarlo bien solo el ancho o la altura (si sólo la altura, a continuación, pasar a la anchura como nulo o no definido) y va a cambiar el tamaño de mantener la relación de aspecto

1

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

probar este ..

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

en el cuadro de texto darle la dimensión como ur deseo, en el formato 50 * 60. Haga clic en enviar. Obtendrás la imagen redimensionada. Dale a tu imagen la ruta en lugar de puntos en la etiqueta de la imagen.

2

No tiene que hacerlo con Javascript. Solo puede crear una clase CSS y aplicarla a su etiqueta.

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

Ejemplo: cómo cambiar el tamaño con un porcentaje

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

para cambiar el tamaño de imagen en 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 es el nombre de la imagen:

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

Tengo answered esta búsqueda aquí: How to resize images proportionally/keeping the aspect ratio?. Copio aquí porque realmente creo que es un método muy fiable :)

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

    var ratio = [maxWidth/srcWidth, maxHeight/srcHeight ]; 
    ratio = Math.min(ratio[0], ratio[1]); 

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

¡Buen trabajo, útil! – mattsven

1

esto funciona para todos los casos

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

}

+0

Este funciona para mí :) Gracias. –

0

Aquí está mi solución de relleno de la cubierta (similar a de fondo: tapa, pero es compatible con el navegador IE anterior)

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