timthumb同样插件为ruby on rails

时间:2011-09-06 00:29:49

标签: ruby-on-rails

对于PHP,有一个功能强大且易于使用的缩略图调整大小脚本/插件,它允许我执行以下操作:

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

它允许我从外部网站获取图像,然后生成缩略图。

  1. ruby​​在轨道上是否有一个均衡的脚本/插件也可以这样做?

  2. 我找到了这个脚本http://www.cleverleap.com/ruby-thumbnail-generator/,但它是否允许我从外部网站获取图片?

  3. 谢谢!

2 个答案:

答案 0 :(得分:0)

结帐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

没有必要给:remote_url它自己的数据库列,但如果你愿意,你可以。

我还强烈建议您对模型控制器的create方法进行一些访问控制,并对您下载的uri进行内容类型检查,但这是另一个主题。

答案 1 :(得分:0)

我只是将它添加到我的application_helper.rb文件

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

这样称呼

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

这取决于&#39; rmagick&#39;和消化&#39;宝石