Skip to content

Instantly share code, notes, and snippets.

@lucianogiuseppe
Created May 6, 2017 11:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucianogiuseppe/b9e6d1ede2671405fcf3680e96dda84e to your computer and use it in GitHub Desktop.
Save lucianogiuseppe/b9e6d1ede2671405fcf3680e96dda84e to your computer and use it in GitHub Desktop.
Javascript JPEG SOF finder
<!doctype html>
<html>
<head>
</head>
<body>
<input type='file' accept='image/*' onchange='openFile(event)'>
<br>
<span id="sizes"></span>
<br>
<canvas id='output'></canvas>
<script>
var canvas = document.getElementById('output')
var ctx = canvas.getContext("2d")
var sizes = document.getElementById('sizes')
var openFile = function(event) {
var input = event.target;
//JPEG struture: https://en.wikipedia.org/wiki/JPEG
//JPEG headers info: http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/JPEG.html
var reader = new FileReader();
reader.onload = function(){
var int32View = new Uint8Array(reader.result); //read file as bytes array
var sizeSeg = 0, offset=0;
if(int32View[0] == 0xff && int32View[1] == 0xd8) { //check SOI marker
if(int32View[2] == 0xff && (int32View[3] >= 0xe0 && int32View[3] <= 0xef) ) { //check APP0..APP15 marker
sizeSeg = (int32View[4]*256)+int32View[5]; //segment size
offset = 4 + sizeSeg;
var eof = false; //End Of File
//while EOF
while(!eof && offset < reader.result.byteLength ) {
if(int32View[offset] != 0xff) {
alert("bad segment");
break;
}
if(int32View[offset+1] == 0xd9) {
alert("JPEG EOI!");
break;
}
//check SOF0...SOF15 segment marker
if(int32View[offset+1] >= 0xc0 && int32View[offset+1] <= 0xcf) {
//get image information
var imgH = (int32View[offset+5]*256)+int32View[offset+6];
var imgW = (int32View[offset+7]*256)+int32View[offset+8];
sizes.innerHTML = "Image info: H="+imgH + " - W=" + imgW;
// draw the image
var img = new Image();
img.onload = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(this, 0, 0, img.width, img.height);
}
img.src = URL.createObjectURL(input.files[0]);
eof=true;
} else {
//go to next segment
sizeSeg = (int32View[offset+2]*256)+int32View[offset+3];
offset += 2 + sizeSeg;
}
} //eow
if(offset >= reader.result.byteLength) {
alert("End of File");
}
} else {
alert("Bad APPX");
}
} else {
alert("File is not a JPEG");
}
};
reader.readAsArrayBuffer(input.files[0]);
};
</script>
</body>
</html>
@lucianogiuseppe
Copy link
Author

Javascript code useful to find JPEG image sizes: height and width

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment