Tuesday 22 November 2011

Rails: Aspect fit images

Aspect fitting images with a frame has always been a common requirement across websites that supports image browsing. Here's how I would like to do it in Rails web applications:

app/models/photo.rb

  def aspect_fit(frame_width, frame_height)
    image_width, image_height = self.data_dimension.split('x')
    ratio_frame = frame_width / frame_height
    ratio_image = image_width.to_f / image_height.to_f
    if ratio_image > ratio_frame
      image_width  = frame_width
      image_height = frame_width / ratio_image
    elsif image_height.to_i > frame_height
      image_width = frame_height * ratio_image
      image_height = frame_height
    end
    "width:#{image_width.to_i}px; height:#{image_height.to_i}px;"
  end
Note: self.data_dimension, will return a string of "widthxheight" for a photo. I store it when uploading images. You might also use, Paperclip::Geometry.from_file to get the dimension during run-time.

In Views:

<div class='photo'>
  <img src='<%= @photo.url %>' style='<%= @photo.aspect_fit(500, 500) %>'/>
</div>

Styles:

#photo { position: relative; height: 500px; width: 500px; background-color: black; }
#photo img { position: absolute; bottom: 0; left: 0; right: 0; top: 0; margin: auto; }

That should be it.

No comments:

Post a Comment