Skip to content

Instantly share code, notes, and snippets.

@miketierney
Created April 30, 2009 20:45
Show Gist options
  • Save miketierney/104677 to your computer and use it in GitHub Desktop.
Save miketierney/104677 to your computer and use it in GitHub Desktop.
def image_resizer max, height, width
# capture any nil or 0/less-than-0 objects and set them to the max value, since they need a value.
# Assume max size is desired unless we're told otherwise.
height = height.nil? || height <= 0 ? max : height
width = width.nil? || width <= 0 ? max : width
# Find out if any of the dimensions are bigger than the max size
if height > max || width > max
# isolate the largest dimension -> it doesn't really matter which one we look at, as long as it's the largest
largest_dimension = height > max ? height : width
# find the difference between the two and isolate that, convert to floats so we don't divide by zero
difference = largest_dimension.to_f / max.to_f
# divide the dimensions by that difference and reset the height and width variables. Then convert back to ints and round down
height = (height.to_f / difference).to_i
width = (width.to_f / difference).to_i
end
# this outputs it in a manner that's consistent with use in an image_tag
"#{width}x#{height}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment