【问题标题】:timthumb alike plugin for ruby on rails用于 ruby​​ on rails 的 timthumb 类似插件
【发布时间】:2014-09-26 03:17:06
【问题描述】:

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

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

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

  1. 是否有一个用于 ruby​​ on rails 的平衡脚本/插件可以实现相同的功能?

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

谢谢!

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    查看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 进行内容类型检查,但这本身就是另一个主题。

    【讨论】:

      【解决方案2】:

      我只是将它添加到我的 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) %>
      

      这取决于 'rmagick' 和 'digest' 宝石

      【讨论】:

        猜你喜欢
        • 2011-01-06
        • 1970-01-01
        • 2011-09-03
        • 2015-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多