linuximagemagickpnglibpng

Looking for a method to replace a PNG's transparent background with any other color in Linux without using ImageMagick


When given a png with a transparent background, even without any of it being visible it causes problems with the rest of my code, so I'm looking for a way to remove the transparent background either using an open source solution or the default libpng library - preferably in linux.

I have tried using ImageMagick and it's how I've verified that converting the transparent background to that of any color solves my issues. I'm just looking for a different solution than ImageMagick.


Solution

  • You can do that in many ways. Here's an example using the NetPBM suite and using this red image with a transparent circular hole in the centre:

    enter image description here


    The steps are as follows:


    ppmmake blue 200 100 > background.ppm
    pngtopam -alphapam YOURIMAGE.png > foreground.pam
    pamcomp foreground.pam background.ppm > result.ppm
    pamtopng result.ppm > result.png
    

    TL;DR

    That's all a bit of a palaver, so leverage the power of Unix to chain lots of things done well together and you get:

    pamcomp <(pngtopam -alphapam YOURIMAGE.png) <(ppmmake blue 200 100) | pamtopng - > result.png
    

    enter image description here


    Depending on how your PNG is actually constructed, and at the loss of flexibility in the colour replacing the transparency, you may find this command, which just ditches the alpa channel, is enough:

    pngtopam YOURIMAGE.png | pamtopng - > result.png
    

    Other ways of approaching this might be:


    With PIL/Pillow, that might look like this:

    from PIL import Image
    
    im = Image.open('YOURIMAGE.png')          # open image
    bg = Image.new('RGB',im.size, 'yellow')   # make yellow background, same size
    bg.paste(im, mask=im)                     # composite your image over background
    bg.save('result.png')                     # save result