我正在使用 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);
});
最佳答案
首先,我们需要设置从input
上传img到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=""/>
关于javascript - 上传前如何检查图像尺寸(宽 x 高)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59587154/