javascript - 上传前如何检查图像尺寸(宽 x 高)?
问题描述
我正在使用 JavaScript 代码在 FireBase/FireStore 中上传图像。
核心功能已经可以了,我可以上传,但上传前还需要检查图片的大小。这就是我很乐意得到帮助的地方。
以下是我的重要代码。和行之间的部分:
// Trying to get the size:
和:
// End of trial code.
不管用。
upLdBtn.addEventListener('change', function(e) {
// Get the file.
var artWorkFile = e.target.files[0];
// Trying to get the size:
var img = new Image();
img.onload = function() {
window.alert('Size = ' + this.width + 'x' + this.height);
}
img.src = artWorkFile;
// End of trial code.
DoSomthingUseful(artWorkFile);
});
解决方案
首先,我们需要设置上传 img frominput
到一个img
容器 src,从这个img
元素之后,我们可能会得到图像的原始宽度和高度值。
这是代码片段:
function setSrc(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#proImg').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function () {
setSrc(this);
setTimeout(getImgRatio,300);
});
function getImgRatio(){
var imgStyleProp = getComputedStyle(proImg);
var w =imgStyleProp.width;
var h =imgStyleProp.height;
console.log(w+"/"+h);
}
img{
width:initial;
height:initial;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="imgInp" required="required" class="custom-file-input">
<img id="proImg" src=""/>
推荐阅读
- python - 如何根据日期时间过滤文件?
- bash - 解析命令输出并构建 bash 键值
- telegram-bot - 如何删除电报机器人自己的消息?
- java - 将字符串列表作为 Cucumber 参数传递
- c# - 如何在unity3d中在com上方添加力?
- python - 未找到页面 (404) 正在报告
- facebook-graph-api - 如何从服务器端获取 Instagram Graph API 用户访问令牌
- node.js - 运行 npm login 命令时出现 403 错误?
- pagination - Yii2在点击分页时停止页面重新加载
- vue.js - 在 Vuejs 中刷新页面后,Prop 未传递给路由器组件