【问题标题】:CarrierWave - Set width and max height of imagesCarrierWave - 设置图像的宽度和最大高度
【发布时间】:2013-01-10 06:03:10
【问题描述】:

我使用 CarrierWave,我想将图像的大小调整为 220 像素的宽度和 220 像素的最大高度。 如果我使用process :resize_to_fit => [220,220],可能是宽度不是 220px。我能做什么?

【问题讨论】:

    标签: ruby-on-rails carrierwave minimagick


    【解决方案1】:

    如果我正确解释问题:

    • 对于纵向图像(例如 480 像素宽、640 像素高),您需要将其缩小到 220 像素宽,然后将其裁剪到 220 像素高,从而生成方形图像。

    • 对于横向图像,您可能希望将其缩小到 220 像素宽(因此高度会小于 220 像素)。

    如果正确,您需要一个两步流程:

    1. 调整为 220 像素宽,保留纵横比
    2. 裁剪到 220 像素高(如果是纵向)

    您可以通过使用manipulate! 命令编写自己的处理器来做到这一点(请参阅CarrierWave's own 以获得一些灵感)。

    我想这大概就是你所追求的

    process :resize => [220, 220]
    
    protected
    
    def resize(width, height, gravity = 'Center')
      manipulate! do |img|
        img.combine_options do |cmd|
          cmd.resize width.to_s
          if img[:width] < img[:height]
            cmd.gravity gravity
            cmd.background "rgba(255,255,255,0.0)"
            cmd.extent "#{width}x#{height}"
          end
        end
        img = yield(img) if block_given?
        img
      end
    end
    

    【讨论】:

    • 它在cmd.resize width 行中显示can't convert Fixnum into String
    • 啊。然后将其更改为"#{width}"width.to_s
    • 然后它说undefined method 'write' for "":String
    • 好吧,我想是因为我忘记从块中返回图像了。
    【解决方案2】:

    对 Andy H 答案的改进:

    process :resize => [220, 220]
    
    protected
    
    def resize(width, height, gravity = 'Center')
      manipulate! do |img|
        img.combine_options do |cmd|
          cmd.resize "#{width}"
          if img[:width] < img[:height]
            cmd.gravity gravity
            cmd.background "rgba(255,255,255,0.0)"
            cmd.extent "#{width}x#{height}"
          end
        end
        img = yield(img) if block_given?
        img
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-30
      • 2015-02-15
      • 1970-01-01
      • 2012-03-01
      • 2014-06-21
      • 2014-04-04
      • 2011-08-27
      • 1970-01-01
      相关资源
      最近更新 更多