Flickr样式使用attachment_fu调整大小

时间:2010-02-11 15:04:27

标签: ruby-on-rails attachment-fu

我希望attachment_fu以与flickr,facebook和twitter处理方式类似的方式调整我的缩略图大小:如果我想要一个100x100缩略图,我希望缩略图正好是100x100,任何多余的裁剪,以保持纵横比

有什么想法吗?

4 个答案:

答案 0 :(得分:1)

要设置100x100缩略图,请将以下内容添加到模型中:

  has_attachment :content_type => :image,
                 :storage => IMAGE_STORAGE,
                 :max_size => 20.megabytes,
                 :thumbnails => {
                   :thumb  => '100x100>',
                   :large  => '800x600>',
                 }

(在这个例子中,我创建了一个100x100缩略图,还有800x600'大'尺寸,另外还保留了原始尺寸。)

另外,请记住缩略图可能不完全是100x100;它的最大尺寸为100x100。这意味着如果原件的宽高比为4:3,缩略图将为100x75。我不确定这是不是你的意思是“正好100x100,任何多余的裁剪,以保持纵横比。”

答案 1 :(得分:0)

可以在规范中给出一个裁剪指令:

has_attachment :content_type => :image,
  :thumbnails => {
    :thumb  => '100x100#'
}

Memonic:'#'看起来像裁剪工具。

编辑:更正

has_attachment :content_type => :image,
  :thumbnails => {
    :thumb  => '100x100!'
}

之前的方法适用于Paperclip,它有不同的符号。

答案 2 :(得分:0)

将此添加到您的模型

protected  

  # Override image resizing method  
  def resize_image(img, size)  
    # resize_image take size in a number of formats, we just want  
    # Strings in the form of "crop: WxH"  
    if (size.is_a?(String) && size =~ /^crop: (\d*)x(\d*)/i) ||  
        (size.is_a?(Array) && size.first.is_a?(String) &&  
          size.first =~ /^crop: (\d*)x(\d*)/i)  
      img.crop_resized!($1.to_i, $2.to_i)  
      # We need to save the resized image in the same way the  
      # orignal does.  
      self.temp_path = write_to_temp_file(img.to_blob)  
    else  
      super # Otherwise let attachment_fu handle it  
    end  
  end

并将缩略图大小更改为:

:thumbnails => {:thumb => 'crop: 100x100' }

源:

http://stuff-things.net/2008/02/21/quick-and-dirty-cropping-images-with-attachment_fu/

答案 3 :(得分:0)

我的解决方案是深入研究attachment_fu插件文件夹(vendor / plugins)并编辑rmagick_processor.rb文件。首先我将resize_image重命名为resize_image_internal,然后添加:

  def resize_image(img, size)  
    # resize_image take size in a number of formats, we just want  
    # Strings in the form of "square: WxH"  
    if (size.is_a?(String) && size =~ /^square: (\d*)x(\d*)/i) ||  
        (size.is_a?(Array) && size.first.is_a?(String) &&  
          size.first =~ /^square: (\d*)x(\d*)/i)  
        iw, ih = img.columns, img.rows
        aspect = iw.to_f / ih.to_f
        if aspect > 1
            shave_off = (iw - ih) / 2
            img.shave!(shave_off, 0)
        else
            shave_off = (ih-iw) / 2
            img.shave!(0, shave_off)
        end
        resize_image_internal(img, "#{$1}x#{$2}!")
    else  
      resize_image_internal(img, size) # Otherwise let attachment_fu handle it  
    end  
  end

我现在可以使用'square:100x100'作为我的几何字符串。请注意,上面的代码假定所需的输出是方形的。