0

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
MegaTux
  • 1,591
  • 21
  • 26
  • 2
    What would a .jpg with rounded corners look like for you? Please post one you have created manually. The JPEG format does not support transparency, so there are limitations (you will need to place background colour in the corners, not use an opacity channel). – Neil Slater Jan 28 '14 at 13:50
  • Fair enough, I'll redo the question. The generated PNG file does not have the rounded corners but the written image does. Thanks Neil! – MegaTux Jan 28 '14 at 17:34
  • 1
    OK, looking through the question again, it seems it is not 100% clear what the end result is supposed to be if original image is a JPEG. I am definitely confused by your direct writing out of the image in JPEG format in the middle of the filter - I am not sure what you are expecting to see in that case. If you are converting JPEG -> PNG, and wish to keep the PNG, then you may also need to add an alpha channel after the conversion (I don't know CarrierWave, so not sure if the conversion is a provided filter or one you have added). – Neil Slater Jan 28 '14 at 18:45
  • 1
    This may be relevant: https://groups.google.com/forum/#!msg/carrierwave/NzJBXMgul9I/mpqLGkwGDJoJ – Neil Slater Jan 28 '14 at 18:53
  • Thanks Neal!, same problem and very similar code. Sadly the post is from 5/24/11 and no responses so far :(. I'll post something there and try luck. – MegaTux Jan 29 '14 at 13:34

0 Answers0