JS实现图片预览与等比缩放

时间:2022-05-24 05:56:19

案例仅为图片预览功能,省略图片上传步骤,框架为easyui。

HTML代码:

 @*text-align:center;水平居中
vertical-align: middle;display: table-cell;垂直居中*@
<div id="img-dialog" style="text-align:center;vertical-align: middle;display: table-cell;padding:5px;">
  <img id="showImg" />
</div> <a href="javascript:void(0)" id="btnShow" onclick="showImga()"></a>

JS代码:

//图片预览
function showImga() {
//显示图片
$("#showImg").attr("src", "../UploadFile/Images/图片.png");
var img = new Image();
img.src = $('#showImg').attr("src");
var w = img.width; //获取图片实际宽度
var h = img.height;
var objImg = $("#showImg")[0];
var maxWidth = 500;
var maxHeight = 500;
autoResizable(w, h, maxWidth, maxHeight, objImg); $('#img-dialog').dialog({
title: '图片预览',
width: maxWidth,
height: maxHeight,
resizable: true, //设置窗体大小可拖动
onResize: function (width, height) { //窗体大小发生改变时触发
//这里为了显示完整图片,需减去easyui本身弹框dialog边框所占高度
autoResizable(w, h, width - 25, height - 35, objImg);
}
});
} //自动调整图片大小
//参数:图片宽度,图片高度,窗体宽度,窗体高度,图片对象
function autoResizable(w, h, maxWidth, maxHeight, objImg) {
var hRatio;
var wRatio;
var Ratio = 1;
wRatio = maxWidth / w;
hRatio = maxHeight / h;
if (maxWidth == 0 && maxHeight == 0) {
Ratio = 1;
} else if (maxWidth == 0) {
if (hRatio < 1) Ratio = hRatio;
} else if (maxHeight == 0) {
if (wRatio < 1) Ratio = wRatio;
} else if (wRatio < 1 || hRatio < 1) {
Ratio = (wRatio <= hRatio ? wRatio : hRatio);
}
if (Ratio < 1) {
w = w * Ratio;
h = h * Ratio;
} objImg.style.height = Math.round(h) + "px";
objImg.style.width = Math.round(w) + "px";
}

最终效果图:

JS实现图片预览与等比缩放