js 图片加载时 按比例设置图片宽高_JS实现按比例缩小图片宽高

本文实例为大家分享了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;

}

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值