0

I have the following code to convert PNG to JPG using Ruby RMagick and the converted image always have a border around it. Anyway to avoid it?

  • Mac OS X 10.8.2
  • ruby 1.9.3p286 (2012-10-12 revision 37165) [x86_64-darwin12]
  • rmagick (2.13.1)
  • MacPorts 2.1.2
  • ImageMagick @6.8.0-2_0+q8+wmf (active)

Here is my code in irb:

irb(main):013:0* image = Magick::Image.read('term.png').first
=> term.png PNG 684x716 684x716+0+0 DirectClass 8-bit 48kb
irb(main):014:0> image.format = "JPG"
=> "JPG"
irb(main):015:0> image.write 'term.jpg'
=> term.png=>term.jpg JPG 684x716 684x716+0+0 DirectClass 8-bit 16kb

and here are the image before and after:

  • BEFOE:

enter image description here

  • AFTER:

enter image description here

TX T
  • 817
  • 2
  • 16
  • 25

2 Answers2

2

The original png image has a transparency channel (the transparent border around the window). Jpg-images do not support transparency. Hence ImageMagick has to do something to the transparency when converting to jpg. In your case it converts the alpha channel to black.

To change the default background color you can do something like this:

i = Magick::ImageList.new
i.read('term.png')
i.new_image(i.first.columns, i.first.rows) { self.background_color = "white" }
i = i.reverse.flatten_images
i.format = "JPG"
i.write('term.jpg')

This creates a composite image with a white background. It then flattens (combines the two images: white background + original image) the composition and writes it out as jpg.

Casper
  • 33,403
  • 4
  • 84
  • 79
0

JPG files do not have an alpha channel, therefore cannot have any pixels that are transparent or semi-transparent. The border is just that fading black regular border, turned opaque by the file transition.