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?
Asked
Active
Viewed 1,518 times
0

ijo
- 55
- 8
2 Answers
3
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:
- Resize to 220px wide, preserving the aspect ratio
- 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

Andrew Haines
- 6,574
- 21
- 34
-
It says `can't convert Fixnum into String` in the line `cmd.resize width`. – ijo Jan 09 '13 at 18:32
-
Ah. Then change it to `"#{width}"` or `width.to_s`. – Andrew Haines Jan 09 '13 at 18:47
-
But then it says `undefined method 'write' for "":String` – ijo Jan 09 '13 at 18:58
-
Ok, I think it was because I forgot to return image from the block. – Andrew Haines Jan 09 '13 at 22:03
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

Bruno
- 71
- 1
- 6