If you want to accomplish this task, you can utilize the File API from the W3C on browsers that support it. By using the File API and the readAsDataURL
function with the FileReader
interface, you can set the data URL as the src
of an img
element to then read its dimensions. Currently, Firefox 3.6 has support for the File API, while Chrome and Safari are either already equipped or soon will be.
During the transitioning period, your approach would involve:
Detecting if the browser supports the File API (easily done with:
if (typeof window.FileReader === 'function')
).
If supported, proceed to read the data locally and display it in an image to obtain its dimensions.
If not supported, upload the file to the server (possibly through submitting the form from an iframe to prevent page redirection), and then communicate with the server to determine the image's size or retrieve the uploaded image.
Edit I have been planning to create a File API example for some time now, 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("Could not locate the imgfile element.");
}
else if (!input.files) {
write("This browser does not 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);
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>
This code snippet functions smoothly on Firefox 3.6. It refrains from utilizing any library, hence the use of attribute-style event handlers and similar approaches.