Check image width and height before upload with Javascript
The file is just a file, you need to create an image like so:
var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
var objectUrl = _URL.createObjectURL(file);
img.onload = function () {
alert(this.width + " " + this.height);
_URL.revokeObjectURL(objectUrl);
};
img.src = objectUrl;
}
});
Demo: http://jsfiddle.net/4N6D9/1/
I take it you realize this is only supported in a few browsers. Mostly firefox and chrome, could be opera as well by now.
P.S. The URL.createObjectURL()
method has been removed from the MediaStream
interface. This method has been deprecated in 2013 and superseded by assigning streams to HTMLMediaElement.srcObject
. The old method was removed because it is less safe, requiring a call to URL.revokeOjbectURL()
to end the stream. Other user agents have either deprecated (Firefox) or removed (Safari) this feature feature.
For more information, please refer here.
Get file size, image width and height before upload
Multiple images upload with info data preview
Using HTML5 and the File API
Example using URL API
The images sources will be a URL representing the Blob object<img src="blob:null/026cceb9-edr4-4281-babb-b56cbf759a3d">
const EL_browse = document.getElementById('browse');const EL_preview = document.getElementById('preview');
const readImage = file => { if ( !(/^image\/(png|jpe?g|gif)$/).test(file.type) ) return EL_preview.insertAdjacentHTML('beforeend', `Unsupported format ${file.type}: ${file.name}<br>`);
const img = new Image(); img.addEventListener('load', () => { EL_preview.appendChild(img); EL_preview.insertAdjacentHTML('beforeend', `<div>${file.name} ${img.width}×${img.height} ${file.type} ${Math.round(file.size/1024)}KB<div>`); window.URL.revokeObjectURL(img.src); // Free some memory }); img.src = window.URL.createObjectURL(file);}
EL_browse.addEventListener('change', ev => { EL_preview.innerHTML = ''; // Remove old images and data const files = ev.target.files; if (!files || !files[0]) return alert('File upload not supported'); [...files].forEach( readImage );});
#preview img { max-height: 100px; }
<input id="browse" type="file" multiple><div id="preview"></div>
Is it possible to check dimensions of image before uploading?
You could check them before submitting form:
window.URL = window.URL || window.webkitURL;
$("form").submit( function( e ) {
var form = this;
e.preventDefault(); //Stop the submit for now
//Replace with your selector to find the file input in your form
var fileInput = $(this).find("input[type=file]")[0],
file = fileInput.files && fileInput.files[0];
if( file ) {
var img = new Image();
img.src = window.URL.createObjectURL( file );
img.onload = function() {
var width = img.naturalWidth,
height = img.naturalHeight;
window.URL.revokeObjectURL( img.src );
if( width == 400 && height == 300 ) {
form.submit();
}
else {
//fail
}
};
}
else { //No file was input or browser doesn't support client side reading
form.submit();
}
});
This only works on modern browsers so you still have to check the dimensions on server side. You also can't trust
the client so that's another reason you must check them server side anyway.
How to validate image size, height, width and format before upload with jquery of PHP?
You can use jQuery to achieve this.
Demo code
Once write a normal code input type ="file" and write down their id in below jQuery.
$(document).ready(function(){
var _URL = window.URL || window.webkitURL;
$('#file').change(function () {
var file = $(this)[0].files[0];
img = new Image();
var imgwidth = 0;
var imgheight = 0;
var maxwidth = 640;
var maxheight = 640;
img.src = _URL.createObjectURL(file);
img.onload = function() {
imgwidth = this.width;
imgheight = this.height;
$("#width").text(imgwidth);
$("#height").text(imgheight);
if(imgwidth <= maxwidth && imgheight <= maxheight){
var formData = new FormData();
formData.append('fileToUpload', $('#file')[0].files[0]);
$.ajax({
url: 'upload_image.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function (response) {
if(response.status == 1){
$("#prev_img").attr("src","upload/"+response.returnText);
$("#prev_img").show();
$("#response").text("Upload successfully");
}else{
$("#response").text(response.returnText);
}
}
});
}else{
$("#response").text("Image size must be "+maxwidth+"X"+maxheight);
}
};
img.onerror = function() {
$("#response").text("not a valid file: " + file.type);
}
});
});
check hight width of image using javascript for multiple file uploads
//html code
<input type='file' name='images[]' id='image' multiple>
//javascript code
$("#image").change(function () {
var this_image = $(this);
var img = document.getElementById('image').files;
var img_len = img.length;
for(var i=0;i<img_len;i++)
{
var this_img = document.getElementById('image').files[i];
var reader = new FileReader();
//Read the contents of Image File.
reader.readAsDataURL(document.getElementById('image').files[i]);
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;
//Validate the File Height and Width.
image.onload = function () {
var height = this.height;
var width = this.width;
console.log(height+"---"+width);
};
}
});
Validate uploaded files by width and height in JavaScript
Use clientWidth & clientHeight property for width and height and then apply your desired condition.
var img = document.getElementById('files');
img.addEventListener('change', function() {
const allowedExtensions = ['jpg'],
sizeLimit = 150000;
const { name:fileName, size:fileSize } = this.files[0];
const fileExtension = fileName.split(".").pop();
//gettting height & width
var width = img.clientWidth;
var height = img.clientHeight;
let alrt = "";
if(!allowedExtensions.includes(fileExtension)){
alrt += "This is not a valid image! \n";
}
debugger;
if(fileSize > sizeLimit){
alrt += "This is not a valid image! \n";
}
if(width != 200 && height != 20 ){ //checking height & width
alrt += "not a valid dimention! \n";
}
if(alrt){
alert(alrt);
img.value = null;
return false;
}
else{
alert("upload successful!");
return true;
}
});
<input type="file" id="files" class="box_file">
Related Topics
How Is Almost Everything in JavaScript an Object
How to Output an Iso 8601 Formatted String in JavaScript
Getting All Variables in Scope
Access Object Child Properties Using a Dot Notation String
Recurring Events in Fullcalendar
How to Edit a JavaScript Alert Box Title
Jquery .Ready in a Dynamically Inserted Iframe
Call an Asynchronous JavaScript Function Synchronously
How to Prevent Enter Keypress to Submit a Web Form
What Does a Tilde Do When It Precedes an Expression
Call ASP.NET Function from JavaScript
Why Does the Month Argument Range from 0 to 11 in JavaScript's Date Constructor
Es6 Modules: Export Single Class of Static Methods or Multiple Individual Methods
How to Bind Fancybox to Dynamic Added Element
How to Find Events Bound on an Element with Jquery
Underscore Template Throwing Variable Not Defined Error
Is There a More Accurate Way to Create a JavaScript Timer Than Settimeout