Skip to content

Instantly share code, notes, and snippets.

@punund
Created November 11, 2012 19:57
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 punund/4056060 to your computer and use it in GitHub Desktop.
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
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()
@punund
Copy link
Author

punund commented Nov 11, 2012

Use it like

getImageSize 'http://my.remote.server/image.jpg', (error, hw, image) ->
  unless error
    console log "height: #{hw[0]}"
    console log "width: #{hw[1]}"

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