4

I need to get the size of an image in Ruby on Rails. The image is in a remote URL. I dont want to download the entire image.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
Tony
  • 10,088
  • 20
  • 85
  • 139
  • I need the info server side, the images are in a remote URL (i.e. Facebook). I need to store just the link in my database, together with width and height, but without downloading it. – Tony Oct 19 '12 at 13:17
  • 1
    The size of images is usually in their header, so unless you have a server serving the information you need (i.e. read the header and give you the dimensions) this cannot be done. – code-gijoe Oct 19 '12 at 13:31
  • 1
    This [post][1] covers pretty much what you need to know. [1]: http://stackoverflow.com/questions/11962445/validating-or-reading-a-remote-image-type-in-javascript – code-gijoe Oct 19 '12 at 13:35

3 Answers3

6

You will most likely not be able to do so without actually downloading the image (as in using the bandwidth).

That being said, you can use the FastImage gem to do this for you.

require 'fastimage'

FastImage.size("http://stephensykes.com/images/ss.com_x.gif")
=> [266, 56]  # width, height
gmalette
  • 2,439
  • 17
  • 26
1

A HTTP header only request won't help you

$ http -h get "http://cdn.sstatic.net/stackoverflow/img/sprites.png"
HTTP/1.1 200 OK
Cache-Control: max-age=604800
Connection: close
Content-Length: 16425
Content-Type: image/png
Date: Fri, 19 Oct 2012 13:39:15 GMT
ETag: "0d1523d7cadcd1:0"
Last-Modified: Thu, 18 Oct 2012 22:02:18 GMT
Server: NetDNA-cache/2.2

So you will need some of the HTTP response body. But some image file formats have header at the top describing the resolution (although jpeg doesn't). So maybe you could make a partial HTTP request (range request) for that bit.

Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
  • If I remember right, canceling the request isn't a good solution on a busy system. It ties up resources in the IP stack, probably on both the client and the host. – the Tin Man Oct 19 '12 at 15:11
0

"Validating or reading a remote image type in javascript" covers pretty much what you need to know. It might be a bit deeper then you really need but it's well explained.

Otherwise, you can create a server-side controller to do this only once. You can read the images and their dimensions from wherever you get them. When users fetch images, the dimensions will be read from your server 'cache' without downloading the image size again. If the information about that particular image is not available you will fetch it and store the dimensions and URL. This could save a lot of bandwidth.

Community
  • 1
  • 1
code-gijoe
  • 6,949
  • 14
  • 67
  • 103