I need to create a PNG version of an image with rounded corners. So far, it only works with PNG source files, not with JPEG ones. I do a conversion of the image to PNG before the composition with the transparent rounded mask. If I write a copy of the image to disk, it always has the correct effect applied, but the output file for carrierwave doesn't.
class AppIconUploader < ImageUploader
include Magick
include ERB::Util
ICON_SIZE = [96, 96]
def default_url
"http://placehold.it/%dx%d&text=%s" % [ICON_SIZE, h(model.name)].flatten
end
version :home do
process :resize_to_fill => ICON_SIZE
process :convert => 'png'
process :rounded_corners
end
def filename
super.chomp(File.extname(super)) + '.png' if original_filename.present?
end
private
def rounded_corners(radius = 15)
manipulate! do |img|
cols, rows = img.columns, img.rows
mask = ::Magick::Image.new(img.columns, img.rows).matte_floodfill(1, 1)
Draw.new.stroke('none').stroke_width(0).fill('white').
roundrectangle(0, 0, cols, rows, radius, radius).
draw(mask)
img.composite!(mask, 0, 0, Magick::CopyOpacityCompositeOp)
img = yield(img) if block_given?
img.write 'output.png' # just write the image to disk to _test_ the result. Image has rounded corners! but not the output to carrierwave.
img
end
end
end