DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

On-the-fly Thumbnailer Method For A Rails 'Photo' Controller

04.08.2005
| 9634 views |
  • submit to reddit
        
require 'RMagick'

class PhotoController < ApplicationController

[...snip...]

    def render_resized_image
                @photo=Photo.find(@params["id"])

                maxw = @params["width"] != nil ? @params["width"].to_i : 90
                maxh = @params["height"] != nil ? @params["height"].to_i : 90
                aspectratio = maxw.to_f / maxh.to_f


                pic = Magick::Image.from_blob(@photo.image)[0]


                picw = pic.columns
                pich = pic.rows
                picratio = picw.to_f / pich.to_f

                if picratio > aspectratio then
                        scaleratio = maxw.to_f / picw
                else
                        scaleratio = maxh.to_f / pich
                end

                #breakpoint

                thumb = pic.resize(scaleratio)

                @response.headers["Content-type"]=@photo.mime
    end
end
<p>Requires <a href="http://rmagick.rubyforge.org/">RMagick</a></p>
<p>Based on <a href="http://www.bigbold.com/snippets/posts/show/36">Thumbnailer in Ruby and RMagick</a></p>