Saturday, December 12, 2015

Convert GIF Background from Transparency to a Solid Color

Preface

Last day, I got a new Pebble watch, then I started to code something on it. Within one day, I've tried out its dictation API with a small but fun app. Also, I wrote a watchface which has a circle progress bar showing the percentage of the time had past today (the idea is from one of Apple Watch watchface, "Solar").

However, when I was trying to put the animation on my watchface, it requires an "Animated Portable Network Graphics (APNG) file format" with solid color background. Therefore, I have to somehow find a way to convert one GIF file I have into that format while my GIF file is having a transparent background.

Steps

"Convert" written by ImageMagick is a powerful tool in this situation, I've been using it from the first year I started to use unix-like systems. To install (for Mac):
> sudo port install ImageMagick
To fill solid background (I use black here) on my GIF file:
> convert input.gif -background black -alpha remove result.gif
where option background sets the color of background, and option alpha is set to "remove" for removing its transparency.

And, to convert GIT file into APNG file, we can use a tool called gif2apng. It can be downloaded here. How I use it is written below:
> unzip gif2apng-1.9-bin-macosx.zip
> cp gif2apng ~/bin
> export PATH=~/bin:$PATH # this depends on the setting you prefer, I like to put this kind of tool under ~/bin
> gif2apng result.gif result.png

gif2apng 1.9 using 7ZIP with 15 iterations

Reading 'result.gif'...
9 frames.
Writing 'result.png'...
9 frames.

More

One to step to go in order to fit into the Pebble Watch, which may be a little irrelevant to this post. I have to crop the image since it's too big. And, what I wanted to do is to remove the upper part. It's originally at size of 100 * 120, and I would like it became 100 * 100. So, there's the magic:
> convert input.gif -coalesce -repage 0x0 -crop 100x100+0+20 +repage result.gif
Finally, we can combine all together as below:
> convert input.gif -coalesce -repage 0x0 -crop 100x100+0+20 +repage -background black -alpha remove result.gif; gif2apng result.gif input.png

No comments:

Post a Comment