/**
* @param imgObj 缩放图片源对象
* @param maxWidth 允许缩放的最大宽度
* @param maxHeight 允许缩放的最大高度
* @usage 使用方式,在img标签中加入onload事件
* http://www.baidu.com/test.jpg 是图片地址,拼接上?t=Math.random()是为了避免图片缓存问题
* <img src="http://www.baidu.com/test.jpg?t=Math.random()" onload="javascript:drawImage(this,300,150)">
*/
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;
}
}
// 设置该img图片的宽和高
imgObj.height = tempHeight;
imgObj.width = tempWidth;
// 提示图片原来的大小
imgObj.alt = image.width + "x" + image.height;
}
}
前端页面上的标签进行调用的写法
img标签的src可以进行动态赋值
<div>
<img id="previewPicture" src="#" alt="" onload="javascript:drawImage(this,300,150)"/>
</div>