Getting Image Dimensions Using JavaScript File API

Getting image dimensions using the JavaScript File API

Yes, read the file as a data URL and pass that data URL to the src of an Image: http://jsfiddle.net/pimvdb/eD2Ez/2/.

var fr = new FileReader;

fr.onload = function() { // file is loaded
var img = new Image;

img.onload = function() {
alert(img.width); // image is loaded; sizes are available
};

img.src = fr.result; // is the data URL because called with readAsDataURL
};

fr.readAsDataURL(this.files[0]); // I'm using a <input type="file"> for demonstrating

Get Image dimensions using Javascript during file upload

You can do this on browsers that support the new File API from the W3C, using the readAsDataURL function on the FileReader interface and assigning the data URL to the src of an img (after which you can read the height and width of the image). Currently Firefox 3.6 supports the File API, and I think Chrome and Safari either already do or are about to.

So your logic during the transitional phase would be something like this:

  1. Detect whether the browser supports the File API (which is easy: if (typeof window.FileReader === 'function')).

  2. If it does, great, read the data locally and insert it in an image to find the dimensions.

  3. If not, upload the file to the server (probably submitting the form from an iframe to avoid leaving the page), and then poll the server asking how big the image is (or just asking for the uploaded image, if you prefer).

Edit I've been meaning to work up an example of the File API for some time; here's one:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show Image Dimensions Locally</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>

function loadImage() {
var input, file, fr, img;

if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}

input = document.getElementById('imgfile');
if (!input) {
write("Um, couldn't find the imgfile element.");
}
else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = createImage;
fr.readAsDataURL(file);
}

function createImage() {
img = document.createElement('img');
img.onload = imageLoaded;
img.style.display = 'none'; // If you don't want it showing
img.src = fr.result;
document.body.appendChild(img);
}

function imageLoaded() {
write(img.width + "x" + img.height);
// This next bit removes the image, which is obviously optional -- perhaps you want
// to do something with it!
img.parentNode.removeChild(img);
img = undefined;
}

function write(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='imgfile'>
<input type='button' id='btnLoad' value='Load' onclick='loadImage();'>
</form>
</body>
</html>

Works great on Firefox 3.6. I avoided using any library there, so apologies for the attribute (DOM0) style event handlers and such.

Determining image file size + dimensions via Javascript?

Edit:

To get the current in-browser pixel size of a DOM element (in your case IMG elements) excluding the border and margin, you can use the clientWidth and clientHeight properties.

var img = document.getElementById('imageId'); 

var width = img.clientWidth;
var height = img.clientHeight;

Now to get the file size, now I can only think about the fileSize property that Internet Explorer exposes for document and IMG elements...

Edit 2: Something comes to my mind...

To get the size of a file hosted on the server, you could simply make an HEAD HTTP Request using Ajax. This kind of request is used to obtain metainformation about the url implied by the request without transferring any content of it in the response.

At the end of the HTTP Request, we have access to the response HTTP Headers, including the Content-Length which represents the size of the file in bytes.

A basic example using raw XHR:

var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'img/test.jpg', true);
xhr.onreadystatechange = function(){
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 ) {
alert('Size in bytes: ' + xhr.getResponseHeader('Content-Length'));
} else {
alert('ERROR');
}
}
};
xhr.send(null);

Note: Keep in mind that when you do Ajax requests, you are restricted by the Same origin policy, which allows you to make requests only within the same domain.

Check a working proof of concept here.

Edit 3:

1.) About the Content-Length, I think that a size mismatch could happen for example if the server response is gzipped, you can do some tests to see if this happens on your server.

2.) For get the original dimensions of a image, you could create an IMG element programmatically, for example:

var img = document.createElement('img');

img.onload = function () { alert(img.width + ' x ' + img.height); };

img.src='http://sstatic.net/so/img/logo.png';

How to get the dimensions of an image selected for a file input on the browser

adding something like this should work

imageUploadInput.onchange = function (event) {
const file = imageUploadInput.files[0];
if (!file) {
return;
}
const image = new Image();
image.onload = function() {
console.log(this.width, this.height);
}
image.src = URL.createObjectURL(file);
};

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>

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.

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 fetch width and height of image javascript

If you want to get the dimensions of the image you can use:

const url = URL.createObjectURL(<File>);
const img = new Image();
img.onload = () => {
// The dimensions will be img.width and img.height
URL.revokeObjectURL(url);
}
img.src = url;


Related Topics



Leave a reply



Submit