检查宽度&使用javascript上传之前图像的高度
本文关键字:图像 高度 使用 javascript 检查 | 更新日期: 2023-09-27 18:13:22
我在网格视图中使用FILE uploader,然后我动态地找到fileuploader的ID。但问题是我得到的值为0的高度&宽度。在我使用的代码下面。
function validateFileSize() {
debugger;
for (var i = 1; i < document.getElementById('<%=gvDocuments.ClientID %>').rows.length; i++) {
var uploadControl = document.getElementById('<%=gvDocuments.ClientID %>').rows[i].cells[3].getElementsByTagName('INPUT')[0].id; //** here i find the ID of File Uploader
if (document.getElementById('<%=gvDocuments.ClientID %>').rows[i].cells[1].getElementsByTagName('SELECT')[0].value == "18")//** here i find the ID of DropDownlist
{
var newImg = new Image();
newImg.src = document.getElementById(uploadControl).value;
var height = newImg.height;
var width = newImg.width;
alert('The Image Dimension is ' + height + ' X ' + width + '');
}
}
}
如果你正在使用jQuery并且你请求像这样的图像大小
检查这个例子
http://jsbin.com/oTAtIpA/3/edit您只需要在image onload函数中检查图像尺寸。
如
newImg.onload = function()
{
var height = this.height;
var width = this.width;
// do stuff with image dimensions
}
参见https://stackoverflow.com/a/626505/53241
《LittleDragon》的例子也是使用纯JavaScript获取尺寸,而不是jQuery
<script type="text/javascript">
$(function () {
$("#upload").bind("click", function () {
//Get reference of FileUpload.
var fileUpload = $("#fileUpload")[0];
//Check whether HTML5 is supported.
if (typeof (fileUpload.files) != "undefined") {
//Initiate the FileReader object.
var reader = new FileReader();
//Read the contents of Image File.
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
//Initiate the JavaScript Image object.
var image = new Image();
//Set the Base64 string return from FileReader as source.
image.src = e.target.result;
image.onload = function () {
//Determine the Height and Width.
var height = this.height;
var width = this.width;
if (height > 100 || width > 100) {
alert("Height and Width must not exceed 100px.");
return false;
}
alert("Uploaded image has valid Height and Width.");
return true;
};
}
} else {
alert("This browser does not support HTML5.");
return false;
}
});
});
</script>
<input type="file" id="fileUpload" />
<input id="upload" type="button" value="Upload" />
试试这个>