Skip to content

Instantly share code, notes, and snippets.

@sstarr
Created August 25, 2010 17:48
Show Gist options
  • Save sstarr/549959 to your computer and use it in GitHub Desktop.
Save sstarr/549959 to your computer and use it in GitHub Desktop.
# Use ImageMagick to get the dimensions of an image
def get_image_dimensions(image_url)
open(image_url, 'rb') do |f|
@image = Magick::Image.from_blob(f.read)
end
"width=\"#{@image.first.columns}\" height=\"#{@image.first.rows}\""
end
# Insert the width and height into all img tags in a string
def insert_image_dimensions(string)
string.scan(/<img (src="(.+?(\.gif|\.jpg|\.png))")(.*?>)/i).each do |result|
dimensions = get_image_dimensions(result[1])
string.sub!(result[0], '\0 ' + dimensions + '\3')
end
return string
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment