Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change picture background color using ImageMagick?

I want to change my picture background color, This is my source http://cdn.mayike.com/emotion/img/attached/1/image/dt/20170916/18/20170916180007_833.png.

If I want to change the background color to another color, what should I do?

If I want to change the background color to transparent, what should I do?

I tried using convert aa.png -background '#0e0e0e' bb.png, but that doesn't work.

like image 249
Yang Avatar asked Sep 28 '17 11:09

Yang


2 Answers

I do not think you will get a perfect result due to the fact that your image is not binary. Nevertheless in Imagemagick you have two choices. First you could just change all white to red:

convert 20170916180007_833.png.jpeg -fuzz 25% -fill red -opaque white -flatten result1.png

enter image description here

Or you can do a flood fill to just change the outer area:

convert 20170916180007_833.png.jpeg -fuzz 25% -fill none -draw "matte 0,0 floodfill" -background red -flatten result2.jpg

enter image description here

like image 91
fmw42 Avatar answered Oct 23 '22 12:10

fmw42


To apply any background color, first the program should know the edges and background. The image you use doesn't do that. Although your command is correct, it doesn't work since edges and background is not distinguished. So we use Masking first

First run this to get edges:

convert aa.png -bordercolor white -border 1x1 \
      -alpha set -channel RGBA -fuzz 20% \
      -fill none -floodfill +0+0 white \
      -shave 1x1    aa.png

Now you'll get the edges saved in aa.png. At this point your background is transparent. Next run the background color change command:

convert aa.png -background blue -flatten bb.png

Now you'll have the expected result.

Output Final Image

Source:http://www.imagemagick.org/Usage/masking/#bg_remove

like image 27
Abhi Avatar answered Oct 23 '22 11:10

Abhi