문제

I use CarrierWave and I want to resize the images to a width of 220px and a max-height of 220px. If I use process :resize_to_fit => [220,220] it could be that the width is not 220px. What can I do?

도움이 되었습니까?

해결책 2

An improvment of Andy H's answer:

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

다른 팁

If I interpret the question correctly:

  • for a portrait image (say 480px wide, 640px high) you would want to scale it down to 220px wide, then crop it down to 220px high, resulting in a square image.

  • for a landscape image, you would want to scale it down to 220px wide (the height would therefore be less than 220px).

If that's right, you want a two-step process:

  1. Resize to 220px wide, preserving the aspect ratio
  2. Crop to 220px high (if portrait)

You can do so by writing your own processor using the manipulate! command (see CarrierWave's own for some inspiration).

I think this is roughly what you're after

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top