[英]How to check image width and height before upload
for picture upload i wrote following html code : 对于图片上传我写了以下HTML代码:
<input type="file" id="upload" class="im" onchange="fileSelectHandlerProfile('defaultProfile','true')" style="cursor:pointer"/>
when we done with select image, 当我们完成选择图像时,
this code will be fired : 此代码将被触发:
function fileSelectHandlerProfile(title, defalutProfile) {
var oFile;
oFile = $('#thumbUploadProfile')[0].files[0];
var rFilter = /^(image\/jpeg|image\/png|image\/gif|image\/bmp|image\/jpg|image\/pjpeg)$/i;
if (!rFilter.test(oFile.type)) {
$('.errorProfile').html('Please select a valid image file (jpg and png are allowed)').show();
}
}
i want to check the oFile width and height, how can it is possible like oFile.type? 我想检查oFile的宽度和高度,怎么可能像oFile.type一样?
A solutions is to load it clienside and check the height and width. 解决方案是将其装入clienside并检查高度和宽度。
function fileSelectHandlerProfile(title, defalutProfile) {
var oFile;
oFile = $('#thumbUploadProfile')[0].files[0];
var rFilter = /^(image\/jpeg|image\/png|image\/gif|image\/bmp|image\/jpg|image\/pjpeg)$/i;
if (!rFilter.test(oFile.type)) {
$('.errorProfile').html('Please select a valid image file (jpg and png are allowed)').show();
}
var picReader = new FileReader();
picReader.addEventListener("load", function (event) {
var imageObj = new Image();
imageObj.src = event.target.result;
imageObj.onload = function () {
//TEST IMAGE SIZE
if (imageObj.height < 100 || imageObj.width < 100) {
$('.errorProfile').html('Please select an image with correct dimensions').show();
}
};
});
//Read the image
picReader.readAsDataURL(oFile);
} }
You can do it in 2 steps: 您可以分两步完成:
var reader = new FileReader();
reader.onloadend = function () {
//var dataUrl = reader.result;
//code as per step 2 here...
}
reader.readAsDataURL(oFile);
//ref: https://developer.mozilla.org/en-US/docs/Web/API/FileReader.readAsDataURL
Now read the image size by creating Image
object with the dataUrl as src. 现在通过使用dataUrl作为src创建Image
对象来读取图像大小。
Details: JS - get image width and height from the base64 code 详细信息: JS-从base64代码获取图像的宽度和高度
The FileReader API allows you to use FileReader.readAsDataURL
to read the file as a data:
url. FileReader API允许您使用FileReader.readAsDataURL
将文件作为data:
url读取。 Use that url as the src
attribute of a <img />
tag and read the width
and height
attribute of that image. 使用该URL作为<img />
标记的src
属性,并读取该图像的width
和height
属性。
var width;
var height;
var oFile;
oFile = $('#thumbUploadProfile')[0].files[0];
var reader = new FileReader();
reader.onload = function(e){
var image = new Image();
image.onload = function(){
width = img.width;
height = img.height;
}
image.src = e.target.result;
};
reader.readAsDataURL(oFile);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.