16

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.

3 Answers 3

14

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

2
  • Thanks for the tip about the floodfill on the draw option ! Super useful.
    – kursus
    Commented Jul 11, 2018 at 15:14
  • 2
    For a PNG with transparent background, convert original.png -background COLOR -flatten -alpha off transparent.png did the job for me: stackoverflow.com/questions/9155377/…
    – mfg
    Commented Apr 13, 2021 at 14:56
11

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

0
7

Usually -opaque, or -transparent, is all that's needed. But because the image is black & white, we need to isolate ROI to effect. I would recommend using the MVG draw commands.

If change to another color, what should I do?

convert 20170916180007_833.png \
        -fill '#0e0e0e' -fuzz 20% \
        -draw 'color 0,0 floodfill' \
        output_color.png

If change to transparent, what should I do?

convert 20170916180007_833.png \
        -fill 'transparent' -fuzz 20% \
        -draw 'color 0,0 floodfill' \
        output_transparent.png

output_transparent.png

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.