Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert PNG with transparency to JPG

Edit: The original title of this question was "Drawbacks of using -flatten option". However, after this question was answered, I decided to change its title, to make it easier found on Google. Also, new title is actually better describes what is told below.

As I discovered today, to convert PNG with transparency into JPG, we need to use -flatten option.

Try it yourself: download Google logo and convert it from PNG to JPG with the following line

convert google.png google.jpg

the picture will be messed:

enter image description here

With -flatten option, it works fine:

convert google.png -flatten google.jpg

I'm wondering are there any drawbacks of using -flatten permanently, for all conversions between PNG, JPG/JPEG and GIF.

like image 581
john c. j. Avatar asked Dec 23 '17 17:12

john c. j.


1 Answers

@John C wrote:

1st approach:
convert google.png -flatten google_flatten.jpg   

2nd approach:
convert google.png -background white -alpha background google_bg_white.png    
convert google_bg_white.png -flatten google_bg_white_flatten.jpg

3rd approach:
convert google.png -background white -alpha remove google_alpharemoveoff.jpg

More properly, these should be

1st approach
convert google.png -background white -flatten google_flatten.jpg

2nd approach
convert google.png -background white -alpha background -flatten google_bg_white_flatten.jpg

3rd approach
convert google.png -background white -alpha remove -alpha off google_alpharemoveoff.jpg


In case 1: -background white is the default. But if you want some other background color you need to specify it.

In case 2: there is no need to save to an intermediate file

In case 3: you will need -alpha off if you save to PNG. JPG does not support transparency, so turning alpha off is not needed.

like image 181
fmw42 Avatar answered Nov 01 '22 00:11

fmw42