【问题标题】:How to set the dimensions for portrait images with the Paperclip gem如何使用 Paperclip gem 设置纵向图像的尺寸
【发布时间】:2012-05-28 12:50:27
【问题描述】:

我正在使用回形针 gem 上传图片,我想同时上传横向和纵向图片。谁能帮我设置两张图片的尺寸。

我的代码是:

has_attached_file :media,
  :styles => {:yplarge=>"440x300>"},
  :path => ":rails_root/public/system/:class/:id/:style/:basename.:extension", 
  :url  => "/system/buzz_pictures/:id/:style/:basename.:extension"

   validates_attachment_size :media, :less_than => 2.megabytes, 
     :message => "Please attach a smaller picture."
   validates_attachment_content_type :media, 
     :content_type=>['image/jpeg', 'image/png', 'image/gif']

此代码适用于横向图像,但不适用于纵向。

【问题讨论】:

  • 但是你想用肖像画做什么?将它们裁剪为“300x440>”?
  • 我想同时上传横向和纵向。
  • 你的意思是你想旋转图片并将其保存为另一种样式?

标签: ruby-on-rails paperclip


【解决方案1】:

只需添加另一种样式:

:styles => {
  :yplarge=>"440x300>",
  :portrait=>"300X440>"
}

根据需要更改值。请注意,如果图像小于给定尺寸,则不会调整其大小。要更改该行为,请将 > 替换为 #。这将强制将图像调整为指定的尺寸。

有关使用不同样式的信息,请参阅回形针文档:

https://github.com/thoughtbot/paperclip/wiki/Thumbnail-Generation

【讨论】:

    【解决方案2】:

    下面的解决方案将保存 2 种样式,如果是横向,则纵向旋转 90,反之亦然。

    has_attached_file :media,
      :styles => {:landscape => Proc.new { |a| { :geometry => "440x300>", :rotation => 90 unless a.landscape? } }, 
                  :portrait => Proc.new { |a| { :geometry => "300x440>", :rotation => 90 if a.landscape? } } }
      :path => ":rails_root/public/system/:class/:id/:style/:basename.:extension", 
      :url  => "/system/buzz_pictures/:id/:style/:basename.:extension",
      :processors => [:rotator]
    
    def landscape?
      Paperclip::Geometry.from_file(to_file(:original)).horizontal?
    end
    
    module Paperclip
      class Rotator < Thumbnail
        def transformation_command
          if rotate_command
            super + rotate_command
          else
            super
          end
        end
    
        def rotate_command
          if @options[:rotation]
            " -rotate #{ @options[:rotation] }"
          end
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2014-04-03
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-13
      相关资源
      最近更新 更多