prawn icon indicating copy to clipboard operation
prawn copied to clipboard

Soft mask doesn't work on PNG with alpha channel

Open lovromazgon opened this issue 7 years ago • 2 comments

I noticed that using a soft mask on a PNG image with an alpha channel doesn't work. In the attached example I tried to make the images round and stroke them with a red circle. It works for the first two images, since one is a JPEG and the other doesn't have an alpha channel. It doesn't work for the last two images, because they have an alpha channel.

Here's a screenshot of the result: image

Source code:

require 'prawn'
require 'open-uri'

class ImageExamplePDF
  include Prawn::View

  def initialize
    @document = Prawn::Document.new
  end

  def generate(image_urls)
    radius = 25
    point = [radius, cursor]

    image_urls.each do |url|
      image = open(url)

      point[0] += radius*2 + 5

      save_graphics_state do

        stroke_color 'ff0000'
        line_width 2
        stroke_circle point, radius

        soft_mask do
          fill_color 0, 0, 0, 0
          fill_circle point, radius
        end

        image image,
              at: [point[0] - radius, point[1] + radius],
              width: 2 * radius,
              height: 2 * radius

      end
    end
  end
end

input = %w[
  https://nzhondas.com/uploads/monthly_2016_01/fallout_avatar.jpg.4c235d182f80f3d1408362a78416c76a.thumb.jpg.85904b88548483496cc914bc897700a2.jpg
  https://cdn2.iconfinder.com/data/icons/social-flat-buttons-3/512/anonymous-512.png
  http://designoholic.com/wp-content/uploads/2017/07/avatar-colored-d.png
  https://vignette.wikia.nocookie.net/justdance/images/a/a6/AC_Avatar_%28UG%29.png
]
pdf = ImageExamplePDF.new
pdf.generate(input)
pdf.render_file 'image_test.pdf'

lovromazgon avatar Aug 15 '18 14:08 lovromazgon

PDF doesn’t support transparent PNG natively. Prawn emulates this by splitting original image into opaque image and a mask containing alpha channel.

Apparently, one mask overrides another. I’m not sure if this is even possible to fix in Prawn (with reasonable effort).

pointlessone avatar Aug 15 '18 15:08 pointlessone

I guess it's related to https://github.com/prawnpdf/prawn/issues/783, where the preferred workaround was:

flattening the files with white background and converting it to 8-bit-per-channel RGB

If this is a known issue I suggest documenting it somewhere and providing the info how to get around it.

lovromazgon avatar Aug 15 '18 17:08 lovromazgon

Something must've happened since this issue has been reported because with the master branch the provided code produces perfectly round images.

pointlessone avatar Jan 22 '24 11:01 pointlessone