开发者

timthumb alike plugin for ruby on rails

For PHP, there is a powerful and easy to use开发者_运维问答 thumbnail-on-the-fly resize script/plugin which allows me to do something like:

http://www.mysite.com/timthumb.php?src=http://www.externalsite.com/image.jpg&h=160&w=300&zc=1&q=100

It allows me to get the image from an external site, then generate thumbnails.

  1. Is there an equilibrium script/plugin for ruby on rails which does the same?

  2. I found this script http://www.cleverleap.com/ruby-thumbnail-generator/, but does it allow me to get image from external sites?

Thanks!


Check out paperclip. Regarding getting images from an external site, using paperclip:

require 'open-uri'

class Photo < ActiveRecord::Base

  attr_accessor :remote_url

  has_attached_file :image, :styles => { :thumb => ["32x32#", :png] }

  before_validation :get_remote_image, :if => :remote_url_provided?
  validates_presence_of :remote_url, :if => :remote_url_provided?, :message => 'is invalid or inaccessible'

  ...

  protected

  def remote_url_provided?
    !self.remote_url.blank?
  end

  def get_remote_image
    self.image = Photo.download_remote_image(self.remote_url)
  end

  def self.download_remote_image (uri)
    io = open(URI.parse(uri))
    def io.original_filename; base_uri.path.split('/').last; end
    io.original_filename.blank? ? nil : io
    rescue 
  end

end

It isn't necessary to give :remote_url it's own database column, but you can if you like.

I'd also highly recommend doing some access control on the create method for your model's controller and content-type checks on the uri you download, but that's another topic on it's own.


I just add this to my application_helper.rb file

def timthumb(src, opts={})
    filename = Digest::MD5.hexdigest src
    thumb_asset_path = asset_path("thumbs/#{filename}.jpg")

    # already exists?
    if Rails.application.assets.find_asset "thumbs/#{filename}.jpg" 
        return thumb_asset_path
    end

    # generate the thumb and cache it
    image = Magick::Image::read(src).first
    image.resize_to_fill!(opts[:w], opts[:h])
    image.write("#{Rails.root}/app/assets/images/thumbs/#{filename}.jpg") {
        self.quality = opts[:q]
    }
    image.destroy!

    return thumb_asset_path
end

call it like so

<%= image_tag timthumb(@my_model_obj.image, w:750, h:481, q:100) %>

It depends on the 'rmagick' and 'digest' gems

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜