まずは、 Mac OS X Lion に brew で cairo をインストール。

インストール先が /usr/local/include や /usr/local/lib じゃないので注意。


$ brew install cairo
==> Installing cairo dependency: pixman
==> Downloading http://cairographics.org/releases/pixman-0.22.2.tar.gz
######################################################################## 100.0%
==> ./configure --prefix=/usr/local/Cellar/pixman/0.22.2 --enable-gtk=no
==> make install
/usr/local/Cellar/pixman/0.22.2: 9 files, 1.0M, built in 23 seconds
==> Installing cairo
==> Downloading http://www.cairographics.org/releases/cairo-1.10.2.tar.gz
######################################################################## 100.0%
==> ./configure --prefix=/usr/local/Cellar/cairo/1.10.2 --with-x
==> make install
==> Caveats
This formula is keg-only, so it was not symlinked into /usr/local.
 
Mac OS X already provides this program and installing another version in
parallel can cause all kinds of trouble.
 
The Cairo provided by Leopard is too old for newer software to link against.
 
Generally there are no consequences of this for you.
If you build your own software and it requires this formula, you'll need
to add its lib & include paths to your build variables:
 
    LDFLAGS  -L/usr/local/Cellar/cairo/1.10.2/lib
    CPPFLAGS -I/usr/local/Cellar/cairo/1.10.2/include
==> Summary
/usr/local/Cellar/cairo/1.10.2: 91 files, 6.5M, built in 59 seconds

PNG画像を読み込んで縦横2倍の大きさに拡大して新しいファイルとして保存するサンプルコード。


#include <string>
#include <cairo/cairo.h>
 
int main(void){
  double factor = 2.0;  
  // load image
  std::string in_path = "input.png";
  cairo_surface_t* in_surface;
  in_surface = cairo_image_surface_create_from_png(in_path.c_str());
  int in_width  = cairo_image_surface_get_width(in_surface);
  int in_height = cairo_image_surface_get_height(in_surface);
  // create image surface
  std::string path = "output.png";
  int width  = (int)(in_width  * factor);
  int height = (int)(in_height * factor);
  cairo_surface_t* surface;
  surface  = cairo_image_surface_create(
    CAIRO_FORMAT_ARGB32, width, height);
  cairo_t* c = cairo_create(surface);
  // draw image
  cairo_scale(c, factor, factor);
  cairo_set_source_surface(c, in_surface, 0.0, 0.0);
  cairo_paint(c);
  // save image
  cairo_status_t status =
    cairo_surface_write_to_png(surface, path.c_str());
  // delete objects
  cairo_destroy(c);
  cairo_surface_destroy(surface);
  cairo_surface_destroy(in_surface);
  return 0;
}

cairo_scale でスケーリング処理をしている。

cairo_matrix_t と cairo_transform を使うともっといろんなアフィン変換が可能っぽい。

コンパイルして実行。


$ g++ -I/usr/local/Cellar/cairo/1.10.2/include -L/usr/local/Cellar/cairo/1.10.2/lib -lcairo ./cairo_scaling_image.cpp
$ ./a.out 

入力画像:
Kohaku, the Whitetiger

出力画像:
Kohaku, the Whitetiger x 2

Ref.
- cairographics.org
- Cairo: A Vector Graphics Library

tags: cairo c++ mac_os_x

Posted by NI-Lab. (@nilab)