猿问

用input 上传图片,怎样获取图片的尺寸大小呢

怎么用js判断图片尺寸?


 <input type="file"  onchange="loadPic(this)"/>

 function loadPic(img){

    consoel.log(img.width);

}


Qyouu
浏览 441回答 1
1回答

FFIVE

我的原理就是和上传预览差不多,简单说下:onchange触发,获取当前file对象(这里可以获取图片的大小、类型、修改时间等)reader去读取文件塞到页面,获取图片的宽高移出图片节点代码,见以下:<input type="file" onchange="getImgInfo(this,getImgInfoCb)"/>function getImgInfo(ev,fnCallBack){&nbsp; &nbsp; &nbsp; &nbsp; var oFile=ev.files[0];&nbsp; &nbsp; &nbsp; &nbsp; var reader=new FileReader();&nbsp; &nbsp; &nbsp; &nbsp; reader.onload=function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 也可以用 window.URL.createObjectURL(this.result)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var oImg=new Image();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; oImg.src=this.result;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.body.appendChild(oImg);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; oImg.onload=function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var imgWidth=oImg.offsetWidth;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var imgHeight=oImg.offsetWidth;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fnCallBack && fnCallBack({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; width:imgWidth,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; height:imgHeight&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.body.removeChild(oImg);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; reader.readAsDataURL(oFile);&nbsp; &nbsp; }&nbsp; &nbsp; function getImgInfoCb(json){&nbsp; &nbsp; &nbsp; &nbsp; console.log(`width:${json.width} , height:${json.height}`);&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答