Pages

From GIF to PNG with ImageMagick

Once you have installed ImageMagick in your environment (on Ubuntu, you could simply install the imagemagick and libmagick++-dev packages via apt-get), it is quite easy write a simple application to test that you have anything ready to work with this handy library.

One of the easiest thing we can do, is converting an existing image from its original format to another one. Let's use this functionality to write a sort of "hello world" application.

I am working in C++ (that's why I have installed the libmagick++-dev package) on a 64 bit Linux-Debian machine (and the Debian part of this explains why I installed the package using apt-get). I am using the GCC C++ compiler, and Eclipse as IDE. So, be prepared to apply some changes to fit the example to your requirements.

I created a new C++ project, adding some information to let the IDE find depending includes and libraries.

In Properties, C/C++ Build, Settings

- In the GCC C++ Compiler, Includes page I added "/usr/include/ImageMagick"
- In the GCC C++ Linker, Libraries page I added:
-L: /usr/lib/x86_64-linux-gnu/
-l: Magick++

So, now Eclipse knows where to find the Magick include directories, and where to find the shareable object libMagick++.so that would be needed to my executable to properly run. If you run ldd on the resulting program file, you will see that it depends also on other Magick shareable objects, namely libMagickWand.so and libMagickCore.so.

I have put in my tmp directory a GIF file, and I want my (silly) little program to convert it to PNG. Here is the code.
#include <Magick++.h>

int main()
{
    Magick::Image image; // 1
    image.read("/tmp/simple.gif"); // 2
    image.write("/tmp/simple.png"); // 3
}
1. An empty Magick image.
2. ImageMagick loads the passed file in an image. What if such file does not exists? A Magick::ErrorBlob exception would be thrown. And since I don't have try-caught my code, this would result in a (small) catastrophe.
3. The image is saved to the new specified file (if the application can actually write it). Notice that Magick is smart enough to understand which format to use accordingly to the passed file name extension.

No comments:

Post a Comment