Created
April 7, 2011 08:43
-
-
Save bytespider/907350 to your computer and use it in GitHub Desktop.
Loads a JPEG image into memory, storing the width and height as properties of a JPEG object using Node.JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
function JPEG(filename) { | |
var image = this; | |
image.blob = null; | |
if (filename) { | |
image = JPEG.loadFromFile(filename); | |
} | |
return image; | |
} | |
JPEG.prototype = { | |
init: function () { | |
try { | |
var dimensions = getDimensions(this.blob); | |
this.width = dimensions.width; | |
this.height = dimensions.height; | |
} catch (e) { | |
console.log(e); | |
process.exit(0); | |
} | |
}, | |
width: 0, | |
height: 0, | |
blob: null | |
}; | |
JPEG.loadFromFile = function (filename) { | |
var image = new JPEG(); | |
image.blob = fs.readFileSync(filename); | |
image.init(); | |
return image; | |
}; | |
JPEG.loadFromBlob = function (blob) { | |
var image = new JPEG(); | |
image.blob = blob; | |
image.init(); | |
return image; | |
}; | |
function getDimensions(blob) { | |
if (blob[0] != 0xFF || blob[1] != 0xD8) { | |
throw 'Image is not valid: No JPG header found'; | |
return null; | |
} | |
var offset = 2; | |
var blob_size = blob.length; | |
while (offset != blob_size - 1) { | |
var c = blob[offset++], skip = 0; | |
if (offset == blob_size - 1 || c != 0xFF) { | |
throw 'Image is not valid: JPG marker error'; | |
return null; | |
} | |
c = blob[offset++]; | |
if (c == 0xC0) { // frame | |
offset += 3; // length and BPP | |
return { | |
width: blob[offset++] << 8 | blob[offset++], | |
height: blob[offset++] << 8 | blob[offset++] | |
}; | |
} else if (c == 0xC2) { // frame | |
offset += 3; // length and BPP | |
return { | |
width: blob[offset++] << 8 | blob[offset++], | |
height: blob[offset++] << 8 | blob[offset++] | |
}; | |
} else if (c == 0xD9) { | |
throw 'Image is not valid: End of JPG found but no frame data'; | |
} else if (c == 0xDD) { | |
skip = 2; | |
} else if (c >= 0xD0 && c <= 0xD7) { | |
skip = 0; | |
} else { | |
skip = blob[offset++] << 8 | blob[offset++]; | |
skip -= 2; | |
} | |
offset += skip; | |
} | |
} | |
exports.JPEG = JPEG; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment