I noticed when uploading a profile pic to Twitter that its size is checked before upload. Can anyone point me to a solution like this?
Thanks
If you're checking the file size you can use something like uploadify to check the file size before upload.
Checking the actual file dimensions (height / width) may need to be done on the server.
I think it is impossible unless you use a flash. You can use uploadify or swfupload for such things.
I have tested this code in chrome and it works fine.
var x = document.getElementById('APP_LOGO'); // get the file input element in your form
var f = x.files.item(0); // get only the first file from the list of files
var filesize = f.size;
alert("the size of the image is : "+filesize+" bytes");
var i = new Image();
var reader = new FileReader();
reader.readAsDataURL(f);
i.src=reader.result;
var imageWidth = i.width;
var imageHeight = i.height;
alert("the width of the image is : "+imageWidth);
alert("the height of the image is : "+imageHeight);
Something like this should cope with forms loaded asynchronously, inputs with or without "multiple" set and avoid the race conditions that happen when using FileReader.readAsDataURL and Image.src.
$('#formContainer').on('change', '#inputFileUpload', function(event) {
var file, _fn, _i, _len, _ref;
_ref = event.target.files;
_fn = function(file) {
var reader = new FileReader();
reader.onload = (function(f) {
return function() {
var i = new Image();
i.onload = (function(e) {
var height, width;
width = e.target.width;
height = e.target.height;
return doSomethingWith(width, height);
});
return i.src = reader.result;
};
})(file);
return reader.readAsDataURL(file);
};
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
file = _ref[_i];
_fn(file);
}
});
Note: Needs jQuery, HTML5, hooks to a structure like:
<div id="formContainer">
<form ...>
...
<input type="file" id="inputFileUpload"></input>
...
</form>
</div>
You need check image Width and Height when Image onload.
var img = new Image;
img.src = URL.createObjectURL(file);
img.onload = function() {
var picWidth = this.width;
var picHeight = this.height;
if (Number(picWidth) > maxwidth || Number(picHeight) > maxheight) {
alert("Maximum dimension of the image to be 1024px by 768px");
return false;
}
}
This works perfectly for me
var _URL = window.URL || window.webkitURL;
$("#file").change(function(e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function() {
if((this.width < 800)||(this.height < 400)){
alert('Image too small. Images must be bigger than 800 x 400');
$('#file').val('');
}
};
img.onerror = function() {
alert( "not a valid file: " + file.type);
};
img.src = _URL.createObjectURL(file);
}
});
Kudos to the original creator: http://jsfiddle.net/4N6D9/1/
I modified this to specify the min width and height of an upload.
Related
I am facing problem for checking height and width for multiple images upload
there is no option for check height & width for image file using:
document.getElementById('id').files;
So I need help to check height & width of multiple uploaded images using JavaScript
//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);
};
}
});
Function for getting image width & height from File object:
function getImageSize(file, callback) {
var reader = new FileReader();
reader.onload = function(e) {
var img = new Image();
img.onload = function(e2) {
callback(img.width, img.height);
}
img.src = e.target.result;
};
reader.readAsDataURL(file);
};
For example, if the file upload input has the id 'inputFile', the following code will print to the console the size of all its images:
var files = document.getElementById('inputFile').files;
for (var i = 0; i < files.length; i++) {
getImageSize(files[i], function(width, height) {
console.log('Image: Width = ' + width + ', height = ' + height);
});
}
Note: it won't necessarily print the images sizes as their order!
As per my previously posted question below which i got answered. I need to get image name along with dimension.
I already tried lot of things to get them but the name and dimension is getting mismatched
How to read(image data / dimension / filesize / name) multiple images on file select?
below is the complete function to get image file information.
fileSelect.addEventListener("change", getSomeFile, false);
function getSomeFile(ev){
var file= ev.target.files;
if (file) {
for(var i=0,f; f = file[i]; i++){
if(!f.type.match('image.*')){continue;}
(function(f){
var reader = new FileReader();
reader.readAsDataURL(file[i]);
reader.onload = function () {
var img = new Image();
img.onload = function() {
var span = document.createElement('span');
span.innerHTML = ['<img id="thumb" src="', img.src,'"/>'].join('');
document.getElementById('mid').appendChild(span, null);
var fileName =f.name;
var fileSize =Math.round(f.size/1024)+' KB';
var imageWidth = img.width;
var imageHeight = img.height;
};
img.src = reader.result;
};
})(file[i]);
}
}
fileSelect.value='';
}
my main goal is to return false out of _validateFile if a File (that is a jpeg) does not have the minimum dimensions. The issue I am having is that it looks like code underneath is getting hit and I can't return false out of _validateFile. I think I have to use a closure but I am not sure. Here is some code:
_validateFile: function(file){
var validDim = 1;
this._helper(file, function(x,y){
if(x < 682 || y < 459){
validDim = 2;
} else{
validDim = 3;
}
});
if(validDim == 2) return false;
else if(validDim == 3) return true;
return true;
},
_helper: function(file, callback){
var fr = new FileReader;
fr.onload = function() {
var img = new Image;
img.onload = function(){
var x = img.width;
var y = img.height;
callback(x,y);
}
img.src = fr.result;
};
fr.readAsDataURL(file);
},
Any pointers in the right direction are greatly appreciated.
Thank you!
you missing '()' to invoke a constructor
var fr = new FileReader();
var img = new Image();
Could you give some detail code about the way you use this object method (_validateFile)?
How can I get the file size, image height and width before upload to my website, with jQuery or JavaScript?
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>
Example using FileReader API
In case you need images sources as long Base64 encoded data strings
<img src="data:image/png;base64,iVBORw0KGg... ...lF/++TkSuQmCC=">
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', `<div>Unsupported format ${file.type}: ${file.name}</div>`);
const reader = new FileReader();
reader.addEventListener('load', () => {
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>`);
});
img.src = reader.result;
});
reader.readAsDataURL(file);
};
EL_browse.addEventListener('change', ev => {
EL_preview.innerHTML = ''; // Clear Preview
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>
Demo
Not sure if it is what you want, but just simple example:
var input = document.getElementById('input');
input.addEventListener("change", function() {
var file = this.files[0];
var img = new Image();
img.onload = function() {
var sizes = {
width: this.width,
height: this.height
};
URL.revokeObjectURL(this.src);
console.log('onload: sizes', sizes);
console.log('onload: this', this);
}
var objectURL = URL.createObjectURL(file);
console.log('change: file', file);
console.log('change: objectURL', objectURL);
img.src = objectURL;
});
If you can use the jQuery validation plugin you can do it like so:
Html:
<input type="file" name="photo" id="photoInput" />
JavaScript:
$.validator.addMethod('imagedim', function(value, element, param) {
var _URL = window.URL;
var img;
if ((element = this.files[0])) {
img = new Image();
img.onload = function () {
console.log("Width:" + this.width + " Height: " + this.height);//this will give you image width and height and you can easily validate here....
return this.width >= param
};
img.src = _URL.createObjectURL(element);
}
});
The function is passed as ab onload function.
The code is taken from here
Here is a pure JavaScript example of picking an image file, displaying it, looping through the image properties, and then re-sizing the image from the canvas into an IMG tag and explicitly setting the re-sized image type to jpeg.
If you right click the top image, in the canvas tag, and choose Save File As, it will default to a PNG format. If you right click, and Save File as the lower image, it will default to a JPEG format. Any file over 400px in width is reduced to 400px in width, and a height proportional to the original file.
HTML
<form class='frmUpload'>
<input name="picOneUpload" type="file" accept="image/*" onchange="picUpload(this.files[0])" >
</form>
<canvas id="cnvsForFormat" width="400" height="266" style="border:1px solid #c3c3c3"></canvas>
<div id='allImgProperties' style="display:inline"></div>
<div id='imgTwoForJPG'></div>
SCRIPT
<script>
window.picUpload = function(frmData) {
console.log("picUpload ran: " + frmData);
var allObjtProperties = '';
for (objProprty in frmData) {
console.log(objProprty + " : " + frmData[objProprty]);
allObjtProperties = allObjtProperties + "<span>" + objProprty + ": " + frmData[objProprty] + ", </span>";
};
document.getElementById('allImgProperties').innerHTML = allObjtProperties;
var cnvs=document.getElementById("cnvsForFormat");
console.log("cnvs: " + cnvs);
var ctx=cnvs.getContext("2d");
var img = new Image;
img.src = URL.createObjectURL(frmData);
console.log('img: ' + img);
img.onload = function() {
var picWidth = this.width;
var picHeight = this.height;
var wdthHghtRatio = picHeight/picWidth;
console.log('wdthHghtRatio: ' + wdthHghtRatio);
if (Number(picWidth) > 400) {
var newHeight = Math.round(Number(400) * wdthHghtRatio);
} else {
return false;
};
document.getElementById('cnvsForFormat').height = newHeight;
console.log('width: 400 h: ' + newHeight);
//You must change the width and height settings in order to decrease the image size, but
//it needs to be proportional to the original dimensions.
console.log('This is BEFORE the DRAW IMAGE');
ctx.drawImage(img,0,0, 400, newHeight);
console.log('THIS IS AFTER THE DRAW IMAGE!');
//Even if original image is jpeg, getting data out of the canvas will default to png if not specified
var canvasToDtaUrl = cnvs.toDataURL("image/jpeg");
//The type and size of the image in this new IMG tag will be JPEG, and possibly much smaller in size
document.getElementById('imgTwoForJPG').innerHTML = "<img src='" + canvasToDtaUrl + "'>";
};
};
</script>
Here is a jsFiddle:
jsFiddle Pick, display, get properties, and Re-size an image file
In jsFiddle, right clicking the top image, which is a canvas, won't give you the same save options as right clicking the bottom image in an IMG tag.
As far as I know there is not an easy way to do this since Javascript/JQuery does not have access to the local filesystem. There are some new features in html 5 that allows you to check certain meta data such as file size but I'm not sure if you can actually get the image dimensions.
Here is an article I found regarding the html 5 features, and a work around for IE that involves using an ActiveX control. http://jquerybyexample.blogspot.com/2012/03/how-to-check-file-size-before-uploading.html
So I started experimenting with the different things that FileReader API had to offer and could create an IMG tag with a DATA URL.
Drawback: It doesn't work on mobile phones, but it works fine on Google Chrome.
$('input').change(function() {
var fr = new FileReader;
fr.onload = function() {
var img = new Image;
img.onload = function() {
//I loaded the image and have complete control over all attributes, like width and src, which is the purpose of filereader.
$.ajax({url: img.src, async: false, success: function(result){
$("#result").html("READING IMAGE, PLEASE WAIT...")
$("#result").html("<img src='" + img.src + "' />");
console.log("Finished reading Image");
}});
};
img.src = fr.result;
};
fr.readAsDataURL(this.files[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" accept="image/*" capture="camera">
<div id='result'>Please choose a file to view it. <br/>(Tested successfully on Chrome - 100% SUCCESS RATE)</div>
(see this on a jsfiddle at http://jsfiddle.net/eD2Ez/530/)
(see the original jsfiddle that i added upon to at http://jsfiddle.net/eD2Ez/)
A working jQuery validate example:
$(function () {
$('input[type=file]').on('change', function() {
var $el = $(this);
var files = this.files;
var image = new Image();
image.onload = function() {
$el
.attr('data-upload-width', this.naturalWidth)
.attr('data-upload-height', this.naturalHeight);
}
image.src = URL.createObjectURL(files[0]);
});
jQuery.validator.unobtrusive.adapters.add('imageminwidth', ['imageminwidth'], function (options) {
var params = {
imageminwidth: options.params.imageminwidth.split(',')
};
options.rules['imageminwidth'] = params;
if (options.message) {
options.messages['imageminwidth'] = options.message;
}
});
jQuery.validator.addMethod("imageminwidth", function (value, element, param) {
var $el = $(element);
if(!element.files && element.files[0]) return true;
return parseInt($el.attr('data-upload-width')) >= parseInt(param["imageminwidth"][0]);
});
} (jQuery));
I have a JPS with a form in which a user can put an image:
<div class="photo">
<div>Photo (max 240x240 and 100 kb):</div>
<input type="file" name="photo" id="photoInput" onchange="checkPhoto(this)"/>
</div>
I have written this js:
function checkPhoto(target) {
if(target.files[0].type.indexOf("image") == -1) {
document.getElementById("photoLabel").innerHTML = "File not supported";
return false;
}
if(target.files[0].size > 102400) {
document.getElementById("photoLabel").innerHTML = "Image too big (max 100kb)";
return false;
}
document.getElementById("photoLabel").innerHTML = "";
return true;
}
which works fine to check file type and size. Now I want to check image width and height but I cannot do it.
I have tried with target.files[0].width but I get undefined. With other ways I get 0.
Any suggestions?
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.
In my view the perfect answer you must required is
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;
//Validate the File Height and Width.
image.onload = function () {
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;
};
};
I agree. Once it is uploaded to somewhere the user's browser can access then it is pretty easy to get the size. As you need to wait for the image to load you'll want to hook into the onload event for img.
Updated example:
// async/promise function for retrieving image dimensions for a URL
function imageSize(url) {
const img = document.createElement("img");
const promise = new Promise((resolve, reject) => {
img.onload = () => {
// Natural size is the actual image size regardless of rendering.
// The 'normal' `width`/`height` are for the **rendered** size.
const width = img.naturalWidth;
const height = img.naturalHeight;
// Resolve promise with the width and height
resolve({width, height});
};
// Reject promise on error
img.onerror = reject;
});
// Setting the source makes it start downloading and eventually call `onload`
img.src = url;
return promise;
}
// How to use in an async function
(async() => {
const imageUrl = 'http://your.website.com/userUploadedImage.jpg';
const imageDimensions = await imageSize(imageUrl);
console.info(imageDimensions); // {width: 1337, height: 42}
})();
Older example:
var width, height;
var img = document.createElement("img");
img.onload = function() {
// `naturalWidth`/`naturalHeight` aren't supported on <IE9. Fallback to normal width/height
// The natural size is the actual image size regardless of rendering.
// The 'normal' width/height are for the **rendered** size.
width = img.naturalWidth || img.width;
height = img.naturalHeight || img.height;
// Do something with the width and height
}
// Setting the source makes it start downloading and eventually call `onload`
img.src = "http://your.website.com/userUploadedImage.jpg";
This is the easiest way to check the size
let img = new Image()
img.src = window.URL.createObjectURL(event.target.files[0])
img.onload = () => {
alert(img.width + " " + img.height);
}
Check for specific size. Using 100 x 100 as example
let img = new Image()
img.src = window.URL.createObjectURL(event.target.files[0])
img.onload = () => {
if(img.width === 100 && img.height === 100){
alert(`Nice, image is the right size. It can be uploaded`)
// upload logic here
} else {
alert(`Sorry, this image doesn't look like the size we wanted. It's
${img.width} x ${img.height} but we require 100 x 100 size image.`);
}
}
Attach the function to the onchange method of the input type file /onchange="validateimg(this)"/
function validateimg(ctrl) {
var fileUpload = ctrl;
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (fileUpload.files) != "undefined") {
var reader = new FileReader();
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var height = this.height;
var width = this.width;
if (height < 1100 || width < 750) {
alert("At least you can upload a 1100*750 photo size.");
return false;
}else{
alert("Uploaded image has valid Height and Width.");
return true;
}
};
}
} else {
alert("This browser does not support HTML5.");
return false;
}
} else {
alert("Please select a valid Image file.");
return false;
}
}
const ValidateImg = (file) =>{
let img = new Image()
img.src = window.URL.createObjectURL(file)
img.onload = () => {
if(img.width === 100 && img.height ===100){
alert("Correct size");
return true;
}
alert("Incorrect size");
return true;
}
}
I think this may be the simplest for uploads if you want to use it other functions.
async function getImageDimensions(file) {
let img = new Image();
img.src = URL.createObjectURL(file);
await img.decode();
let width = img.width;
let height = img.height;
return {
width,
height,
}
}
Use like
const {width, height } = await getImageDimensions(file)
Suppose you were storing an image for Tiger taken in Kenya. So you could use it like to upload to cloud storage and then store photo information.
const addImage = async (file, title, location) => {
const { width, height } = await getImageDimensions(file)
const url = await uploadToCloudStorage(file) // returns storage url
await addToDatabase(url, width, height, title, location)
}
function validateimg(ctrl) {
var fileUpload = $("#txtPostImg")[0];
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (fileUpload.files) != "undefined") {
var reader = new FileReader();
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var height = this.height;
var width = this.width;
console.log(this);
if ((height >= 1024 || height <= 1100) && (width >= 750 || width <= 800)) {
alert("Height and Width must not exceed 1100*800.");
return false;
}
alert("Uploaded image has valid Height and Width.");
return true;
};
}
} else {
alert("This browser does not support HTML5.");
return false;
}
} else {
alert("Please select a valid Image file.");
return false;
}
}
You can do the steps for previewing the image without showing it which is supported on all browsers. Following js code shows you how to check the width and height :
var file = e.target.files[0];
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.src = this.result as string;
image.addEventListener('load', function () {
console.log(`height: ${this.height}, width: ${this.width}`);
});
}, false);
reader.readAsDataURL(file);
}
Based on Mozilla docs:
The readAsDataURL method is used to read the contents of the specified
Blob or File. When the read operation is finished, the readyState
becomes DONE, and the loadend is triggered. At that time, the result
attribute contains the data as a data: URL representing the file's
data as a base64 encoded string.
And the browser compatibility is listed too.
In my case, I needed to also prevent the form from being submited, so here is the solution that worked for me.
The preventDefault will stop the form action, then we check the size and dimensions of the image in the onload function.
If all good, we allow the submit.
As the submit button gets disabled if a user still tries to submit the form with an invalid image, I also had to re-able the submit button once a valid image is inputted.
const validateMaxImageFileSize = (e) => {
e.preventDefault();
const el = $("input[type='file']")[0];
if (el.files && el.files[0]) {
const file = el.files[0];
const maxFileSize = 5242880; // 5 MB
const maxWidth = 1920;
const maxHeight = 1080;
const img = new Image();
img.src = window.URL.createObjectURL(file);
img.onload = () => {
if (file.type.match('image.*') && file.size > maxFileSize) {
alert('The selected image file is too big. Please choose one that is smaller than 5 MB.');
} else if (file.type.match('image.*') && (img.width > maxWidth || img.height > maxHeight)) {
alert(`The selected image is too big. Please choose one with maximum dimensions of ${maxWidth}x${maxHeight}.`);
} else {
e.target.nodeName === 'INPUT'
? (e.target.form.querySelector("input[type='submit']").disabled = false)
: e.target.submit();
}
};
}
};
$('form.validate-image-size').on('submit', validateMaxImageFileSize);
$("form.validate-image-size input[type='file']").on('change', validateMaxImageFileSize);
function uploadfile(ctrl) {
var validate = validateimg(ctrl);
if (validate) {
if (window.FormData !== undefined) {
ShowLoading();
var fileUpload = $(ctrl).get(0);
var files = fileUpload.files;
var fileData = new FormData();
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
fileData.append('username', 'Wishes');
$.ajax({
url: 'UploadWishesFiles',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function(result) {
var id = $(ctrl).attr('id');
$('#' + id.replace('txt', 'hdn')).val(result);
$('#imgPictureEn').attr('src', '../Data/Wishes/' + result).show();
HideLoading();
},
error: function(err) {
alert(err.statusText);
HideLoading();
}
});
} else {
alert("FormData is not supported.");
}
}