这期内容当中小编将会给大家带来有关利用JavaScript实现图片按比例缩小宽高,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
具体内容如下
<!DOCTYPE html>
<html>
<head>
<title>JS 按比例缩小图片宽高</title>
</head>
<body>
<div>
<input type="file" name="" id="upload">
<img src="" alt="" id="preview">
</div>
</body>
<script>
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.onload=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);
})
</script>
</html>
小编再为大家分享一段:图片按宽高比例进行自动缩放代码
/**
* 图片按宽高比例进行自动缩放
* @param ImgObj
* 缩放图片源对象
* @param maxWidth
* 允许缩放的最大宽度
* @param maxHeight
* 允许缩放的最大高度
* @usage
* 调用:<img src="图片" onload="javascript:DrawImage(this,100,100)">
*/
function DrawImage(ImgObj, maxWidth, maxHeight){
var image = new Image();
//原图片原始地址(用于获取原图片的真实宽高,当<img>标签指定了宽、高时不受影响)
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;
}
}
上述就是小编为大家分享的利用JavaScript实现图片按比例缩小宽高了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。