更改 Image() 对象尺寸(宽度和高度)

Change Image() object dimensions (width and height)

本文关键字:高度 Image 对象 更改      更新时间:2023-09-26

我正在尝试调整图像尺寸的大小,同时保留其纵横比。这似乎是一项非常简单的任务,但我在任何地方都找不到答案。(与 JavaScript 的 Image() 对象有关)。我可能错过了一些非常明显的东西。以下是我想要实现的目标:

var img = new window.Image();
img.src = imageDataUrl;
img.onload = function(){
    if (img.width > 200){
        img.width = 200;
        img.height = (img.height*img.width)/img.width;
    }
    if (img.height > 200){
        img.height = 200;
        img.width = (img.width*img.height)/img.height;
    }
};

这是为了在绘制到画布上之前按比例调整图像大小,如下所示:context.drawImage(img,0,0,canvas.width,canvas.height); .但是,我似乎不能直接更改Image()尺寸,那么它是如何完成的呢?谢谢。

编辑:我没有使用交叉乘法正确解决图像比例。 @markE提供了一种获得正确比率的简洁方法。以下是我的新(工作)实现:

var scale = Math.min((200/img.width),(200/img.height));
img.width = img.width*scale;
img.height = img.height*scale;
clearCanvas(); //clear canvas
context.drawImage(img,0,0,img.width,img.height);

以下是按比例缩放图像的方法:

function scalePreserveAspectRatio(imgW,imgH,maxW,maxH){
    return(Math.min((maxW/imgW),(maxH/imgH)));
}

用法:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/balloon.png";
function start(){
  canvas.width=100;
  canvas.height=100;
  var w=img.width;
  var h=img.height;
  // resize img to fit in the canvas 
  // You can alternately request img to fit into any specified width/height
  var sizer=scalePreserveAspectRatio(w,h,canvas.width,canvas.height);
  ctx.drawImage(img,0,0,w,h,0,0,w*sizer,h*sizer);
}
function scalePreserveAspectRatio(imgW,imgH,maxW,maxH){
  return(Math.min((maxW/imgW),(maxH/imgH)));
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<h4>Original Balloon image resized to fit in 100x100 canvas</h4>
<canvas id="canvas" width=100 height=100></canvas>

图像尺寸在构造函数中设置

new Image(width, height)
// for proportionally consistent resizing use new Image(width, "auto")

the context.drawImage() 

参数如下:

context.drawImage(image source, x-coordinate of upper left portion of image,
y-coordinate of upper left portion of image,image width,image height);  

只需使用前两个数字坐标定位图像,然后使用最后两个(宽度,高度)手动调整大小

//ex.
var x = 0;
var y = 0;
var img = new Image (200, "auto");
    img.src = "xxx.png";
context.drawImage(img,x,y,img.width,img.height);