本文实例为大家分享了JS实现按比例缩小图片宽高的具体代码,供大家参考,具体内容如下
JS 按比例缩小图片宽高
var upd =document.getElementById('upload');
upd.addEventListener('change',function(e){
var file=e.target.files[0];
var reader=new FileReader();
var img = document.createElement('img');
var canvas=document.createElement('canvas');
var context=canvas.getContext('2d');
reader.οnlοad=function(e){
img.src = e.target.result;
img.onload = function () {
var imgWidth=this.width;//上传图片的宽
var imgHeight = this.height;//上传图片的高
//按比例缩放后图片宽高
var targetWidth = imgWidth;
var targetHeight = imgHeight;
var maxWidth=1920;//图片最大宽
var maxHeight = 1080;//图片最大高
var scale = imgWidth / imgHeight;//原图宽高比例
//如果原图宽大于最大宽度
if(imgWidth>maxWidth){
targetWidth = maxWidth;
targetHeight = targetWidth/scale;
}
//缩放后高度仍然大于最大高度继续按比例缩小
if(targetHeight>maxHeight){
targetHeight = maxHeight
targetWidth = targetHeight*scale;
}
canvas.width=targetWidth;//canvas的宽=图片的宽
canvas.height=targetHeight;//canvas的高=图片的高
context.clearRect(0,0,targetWidth,targetHeight)//清理canvas
context.drawImage(img,0,0,targetWidth,targetHeight)//canvas绘图
var newUrl=canvas.toDataURL('image',0.92);//canvas导出成为base64
preview.src=newUrl
}
}
reader.readAsDataURL(file);
})
小编再为大家分享一段:图片按宽高比例进行自动缩放代码
/**
* 图片按宽高比例进行自动缩放
* @param ImgObj
* 缩放图片源对象
* @param maxWidth
* 允许缩放的最大宽度
* @param maxHeight
* 允许缩放的最大高度
* @usage
* 调用:
*/
function DrawImage(ImgObj, maxWidth, maxHeight){
var image = new Image();
//原图片原始地址(用于获取原图片的真实宽高,当标签指定了宽、高时不受影响)
image.src = ImgObj.src;
// 用于设定图片的宽度和高度
var tempWidth;
var tempHeight;
if(image.width > 0 && image.height > 0){
//原图片宽高比例 大于 指定的宽高比例,这就说明了原图片的宽度必然 > 高度
if (image.width/image.height >= maxWidth/maxHeight) {
if (image.width > maxWidth) {
tempWidth = maxWidth;
// 按原图片的比例进行缩放
tempHeight = (image.height * maxWidth) / image.width;
} else {
// 按原图片的大小进行缩放
tempWidth = image.width;
tempHeight = image.height;
}
} else {// 原图片的高度必然 > 宽度
if (image.height > maxHeight) {
tempHeight = maxHeight;
// 按原图片的比例进行缩放
tempWidth = (image.width * maxHeight) / image.height;
} else {
// 按原图片的大小进行缩放
tempWidth = image.width;
tempHeight = image.height;
}
}
// 设置页面图片的宽和高
ImgObj.height = tempHeight;
ImgObj.width = tempWidth;
// 提示图片的原来大小
ImgObj.alt = image.width + "×" + image.height;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。