14

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.

fmw42
  • 46,825
  • 10
  • 62
  • 80
Yang
  • 215
  • 1
  • 3
  • 12

3 Answers3

13

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

fmw42
  • 46,825
  • 10
  • 62
  • 80
  • Thanks for the tip about the floodfill on the draw option ! Super useful. – kursus Jul 11 '18 at 15:14
  • For a PNG with transparent background, `convert original.png -background COLOR -flatten -alpha off transparent.png` did the job for me: https://stackoverflow.com/questions/9155377/set-transparent-background-using-imagemagick-and-commandline-prompt – Mario Apr 13 '21 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

Abhinandan
  • 159
  • 1
  • 14
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

emcconville
  • 23,800
  • 4
  • 50
  • 66