LoginSignup
12
12

More than 5 years have passed since last update.

CからImageMagickを利用する

Last updated at Posted at 2013-03-24

CからImageMagickを利用する

MagickWand C API を参考に、CからImageMagickを利用してみる。

事前準備

HomebrewでImageMagickをインストールしておく。

brew install imagemagick

サンプルコード

サンプルとして http://www.imagemagick.org/source/wand.c を利用させてもらう。

中身は指定した画像をサムネイル用の小さな画像へ変換する簡単なプログラムです。

#include <stdio.h>
#include <stdlib.h>
#include <wand/MagickWand.h>

int main(int argc,char **argv)
{
#define ThrowWandException(wand) \
{ \
    char \
        *description; \
 \
    ExceptionType \
        severity; \
 \
    description=MagickGetException(wand,&severity); \
    (void) fprintf(stderr,"%s %s %lu %s\n",GetMagickModule(),description); \
    description=(char *) MagickRelinquishMemory(description); \
    exit(-1); \
}

    MagickBooleanType
        status;

    MagickWand
        *magick_wand;

    if (argc != 3)
        {
            (void) fprintf(stdout,"Usage: %s image thumbnail\n",argv[0]);
            exit(0);
        }
    /*
        Read an image.
    */
    MagickWandGenesis();
    magick_wand=NewMagickWand();    
    status=MagickReadImage(magick_wand,argv[1]);
    if (status == MagickFalse)
        ThrowWandException(magick_wand);
    /*
        Turn the images into a thumbnail sequence.
    */
    MagickResetIterator(magick_wand);
    while (MagickNextImage(magick_wand) != MagickFalse)
        MagickResizeImage(magick_wand,106,80,LanczosFilter,1.0);
    /*
        Write the image then destroy it.
    */
    status=MagickWriteImages(magick_wand,argv[2],MagickTrue);
    if (status == MagickFalse)
        ThrowWandException(magick_wand);
    magick_wand=DestroyMagickWand(magick_wand);
    MagickWandTerminus();
    return(0);
}

コンパイル

wand.c をコンパイル。

cc -o wand `pkg-config --cflags --libs MagickWand` wand.c

pkg-configを使わない場合はこんな感じになる。

cc -o wand -I/usr/local/include/ImageMagick -L /usr/local/lib -lMagickWand-Q16 wand.c

動かしてみる

wand を実行してみる。

./wand sample.jpg thumbnail.jpg

これで sample.jpg のサムネイル用画像が thumbnail.jpg として生成される。

グレイスケール化してみる

オリジナルの wand.c は渡された画像をサムネイル化している。これをグレイスケール化に変更してみる。wand.c を以下のように変更する。

diff --git a/wand.c b/wand.c
index 94f732d..0b3f5eb 100644
--- a/wand.c
+++ b/wand.c
@@ -42,7 +42,7 @@ int main(int argc,char **argv)
     */
     MagickResetIterator(magick_wand);
     while (MagickNextImage(magick_wand) != MagickFalse)
-        MagickResizeImage(magick_wand,106,80,LanczosFilter,1.0);
+        MagickTransformImageColorspace(magick_wand, GRAYColorspace);
     /*
         Write the image then destroy it.
     */

ImageMagickにどんなAPIがあるかは

を見ると良さそう。

参考

12
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12