图片的等比例缩放
<div class="info-item business-license">
<label class="info-label">营业执照</label>
<div class="info-input-wrap">
<div class="license-wrap">
<img class="license-img" id="licenseImg" onload="javascript:DrawImage(this,167,198)" class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="${staticURL }/image/default-license.png" />
</div>
<div class="license-btn">
<span class="license-text">上传营业执照</span>
<input type="file" class="upload-btn" id="uloadBtn1" name="licenseImgFile" accept=".png,.jpg,.jpeg" />
</div>
<div class="license-remove" id="removeLicense">×</div>
</div>
</div>上传图片后img标签展示出来,并等比例缩放,设置最大宽高为167,198;
编写input上传事件,并显示预览图片。
$('#uloadBtn1').on('change', function () {
var files = this.files[0];
var objUrl = showPhoto(this.files[0]);
if (objUrl) {
$("#licenseImg").attr("src", objUrl);
$('.info-input-wrap').addClass('bicense-wrap')
$(this).parents('.license-btn').addClass('license-change');
}
var formData = new FormData();
formData.append('file', $('#uloadBtn1')[0].files[0]); //添加图片信息的参数
})编写图片预览方法
//头像预览
function showPhoto (file) {
var url = null;
if (window.createObjectURL != undefined) { // basic
url = window.createObjectURL(file);
} else if (window.URL != undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file);
}
return url;
}以上实现了选择图片,再页面上预览。再图片加载时,根据图片大小来实现缩放,设置图片显示的大小。使用加载方法。
function DrawImage(ImgObj, maxWidth, maxHeight){
//原图片原始地址(用于获取原图片的真实宽高,当<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){
empWidth = 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;
}
}因图片加载时调用该方法,DrawImage需要再放在最前。
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦