Created
November 11, 2012 19:57
-
-
Save punund/4056060 to your computer and use it in GitHub Desktop.
Retrieves first chunk of data of remote image via HTTP GET to find out its size in pixels. PNG, JPEG
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
getImageSize = (image, cb) -> | |
fromHex = (hex) -> parseInt "0x#{hex}", 16 | |
req = http.request image, (res) -> | |
res.setEncoding 'hex' | |
res.on 'error', (e) -> cb "getImageSize error (#{image}): " + e, null, image | |
res.on 'data', (chunk) -> | |
m = switch res.headers['content-type'] | |
when 'image/jpeg' | |
chunk.match 'ffc0001108(....)(....)' | |
when 'image/png' | |
x = chunk.match '49484452(.{8})(.{8})' # IHDR | |
[null, x[2], x[1]] | |
h = fromHex m?[1] | |
w = fromHex m?[2] | |
if h > 0 and w > 0 | |
cb null, [h, w], image | |
else | |
cb 'getImageSize: bad size(-s)', null, image | |
res.destroy() | |
req.on 'error', (e) -> cb "getImageSize request error (#{image}): " + e, null, image | |
req.end() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use it like