Page 1 of 1

Converting PNG to JPEG - black background

Posted: 2013-09-06T15:57:57-07:00
by femski
Folks !

When I use this simplest command to convert from PNG to JPEG I get a large black area in JPEG file.
convert 10.png 10.jpg

These images are available here:

http://www.metarmap.com/outgoing/10.png
http://www.metarmap.com/outgoing/10.jpg

PNG image is a tile generated using gdal2tile command with nodata value = 51, 51 51.
Tile rendering software handles PNG tiles fine but has large black area when using JPEG tiles.

Whats the correct command to convert above PNG to JPG so the white/transparent area in PNG file is cutout from image ie JPEG file has no black area at all ?

thanks,

-Sanjay

Re: Converting PNG to JPEG - black background

Posted: 2013-09-06T16:07:27-07:00
by fmw42
JPEG does not support transparency. If your PNG images have any transparency, they will be removed and usually leaving black behind. You can change the color to anything you want.

convert image.png -background somecolor -flatten image.jpg

Re: Converting PNG to JPEG - black background

Posted: 2013-09-06T16:12:20-07:00
by glennrp
Add a 1-pixel black frame to the JPG, then -trim to get rid of the black frame and black area.

Code: Select all

convert 10.jpg -bordercolor black -border 1x1 -trim 10-trimmed.jpg

Re: Converting PNG to JPEG - black background

Posted: 2013-09-30T22:22:20-07:00
by anthony
You should use -alpha remove rather than mis-use -flatten.

It has the same effect, but the alpha on is faster and more memory efficient. It also works with "mogrify", where -flatten will not.

Re: Converting PNG to JPEG - black background

Posted: 2013-09-30T22:24:41-07:00
by anthony
glennrp wrote:Add a 1-pixel black frame to the JPG, then -trim to get rid of the black frame and black area.

Code: Select all

convert 10.jpg -bordercolor black -border 1x1 -trim 10-trimmed.jpg
Why one pixel... you can add a zero pixel border ;-)

Code: Select all

convert 10.png -bordercolor black -border 0  10.jpg
This avoid trim which may over trim the image rather than retain the images original size. Also if you use trim you should use +repage after it, though with JPG it isn't necessary it is still a good idea to do it explicitly.

However as mentioned the best way is...

Code: Select all

convert 10.png -background black -alpha remove  10.jpg
It does not generate a second background image and composes the two images. It just composes the background color directly with each pixel.