gpt4 book ai didi

javascript - 减少javascript中保持纵横比的base64图像的尺寸

转载 作者:行者123 更新时间:2023-11-30 19:28:38 25 4
gpt4 key购买 nike

我有一个用于图像的 base64 字符串,我必须将其显示为图标。如果图像的尺寸更大,我必须显示保持纵横比的图标。我已经编写了一个逻辑来根据为 Canvas 设置的高度和宽度来识别图像是横向还是纵向。但是图标的高度和宽度似乎不合适,因为我已经对其进行了硬编码。

      var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var height, width;
if (this.height>this.width) {
height = 50;
width = 30;
} else if (this.height<this.width) {
height = 30;
width = 50;
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(image,
0, 0, this.width, this.height,
0, 0, canvas.width, canvas.height
);
var scaledImage = new Image();
scaledImage.src = canvas.toDataURL();

有没有什么方法可以动态计算它或任何其他方法来保持图标的纵横比。

可以在 https://codepen.io/imjaydeep/pen/ewBZRK 上找到工作示例

enter image description here

如果在x-y轴上留一些空间就好了。

最佳答案

您只需计算比例或比率,然后将两个维度乘以它。这是一个示例函数,这是您的 edited codepen .

创建经过 trim 、缩放的图像:

enter image description here

function scaleDataURL(dataURL, maxWidth, maxHeight){
return new Promise(done=>{
var img = new Image;
img.onload = ()=>{
var scale, newWidth, newHeight, canvas, ctx;
if(img.width < maxWidth){
scale = maxWidth / img.width;
}else{
scale = maxHeight / img.height;
}
newWidth = img.width * scale;
newHeight = img.height * scale;
canvas = document.createElement('canvas');
canvas.height = newHeight;
canvas.width = newWidth;
ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, newWidth, newHeight);
done(canvas.toDataURL());
};
img.src = dataURL;
});
}

或者,如果您希望图像始终为提供的尺寸且周围区域为空,您可以使用此方法:( codepen )

创建精确提供尺寸的缩放图像:

enter image description here

function scaleDataURL(dataURL, maxWidth, maxHeight){
return new Promise(done=>{
var img = new Image;
img.onload = ()=>{
var scale, newWidth, newHeight, canvas, ctx, dx, dy;
if(img.width < maxWidth){
scale = maxWidth / img.width;
}else{
scale = maxHeight / img.height;
}
newWidth = img.width * scale;
newHeight = img.height * scale;
canvas = document.createElement('canvas');
canvas.height = maxWidth;
canvas.width = maxHeight;
ctx = canvas.getContext('2d');
dx = (maxWidth - newWidth) / 2;
dy = (maxHeight - newHeight) / 2;
console.log(dx, dy);
ctx.drawImage(img, 0, 0, img.width, img.height, dx, dy, newWidth, newHeight);
done(canvas.toDataURL());
};
img.src = dataURL;
});
}

关于javascript - 减少javascript中保持纵横比的base64图像的尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56668685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com