您好我有以下代码从输入中获取文件,图像并将其发布到php它一切都很好但我想首先找到图像的高度和宽度。我该怎么做呢?这是我的代码:
$(':file').change(function(){
file = this.files[0];
});
function doit(){
var formData = new FormData($('form')[0]);
//console.log(dataObj);
if(file.name.length < 1) {
TooBig = true
}
else if(file.size > 1000000) {
TooBig = true
}
else if(file.type != 'image/png' && file.type != 'image/jpg' && file.type != 'image/jpeg' ) {
TooBig = true
console.log("done");
}else{
TooBig = false
}
if(TooBig == false){
document.getElementById('submitbtn').innerHTML = 'Uploading';
$.ajax({
url: 'saveImage.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data){
console.log(data);
nextID = data;
cancel2();
}
});
}else{
document.getElementById('thumbage2').value = "";
document.getElementById('labelthumb2').innerHTML = ''+height;
}
}
我尝试使用
file.width;
但它没有用,有人可以帮助我吗? 编辑:我希望在图像仍处于输入字段时获得图像的高度。
答案 0 :(得分:0)
您可以尝试以下代码:
var imageWidth = null;
var imageHeight = null;
$(':file').change(function(){
var windowURL = window.URL || window.webkitURL;
var file = this.files[0];
var image = new Image();
image.src = windowURL.createObjectURL(file);
image.onload = function() {
imageWidth = this.width;
imageHeight = this.height;
};
});
稍后,您可以在imageWidth
函数中使用变量imageHeight
和doit()
进行验证。
因此,您的整个代码如下:
var imageWidth = null;
var imageHeight = null;
$(':file').change(function(){
var windowURL = window.URL || window.webkitURL;
var file = this.files[0];
var image = new Image();
image.src = windowURL.createObjectURL(file);
image.onload = function() {
imageWidth = this.width;
imageHeight = this.height;
};
});
function doit(){
var formData = new FormData($('form')[0]);
//console.log(dataObj);
if(file.name.length < 1) {
TooBig = true;
}
else if(file.size > 1000000) {
TooBig = true;
}
else if(file.type != 'image/png' && file.type != 'image/jpg' && file.type != 'image/jpeg' ) {
TooBig = true;
console.log("done");
} else if(imageWidth > 1700 && imageHeight > 1300) {
TooBig = true;
} else{
TooBig = false;
}
if(TooBig == false){
document.getElementById('submitbtn').innerHTML = 'Uploading';
$.ajax({
url: 'saveImage.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data){
console.log(data);
nextID = data;
cancel2();
}
});
}else{
document.getElementById('thumbage2').value = "";
document.getElementById('labelthumb2').innerHTML = ''+height;
}
}
最后,我对你的建议是坚持编码惯例。它可以帮助您使代码更容易阅读。