Wednesday, July 29, 2009

ImageMagickとPHPで看板を描画する

Imagickで看板を描画するには、以下のコードを実行します。


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja"
xml:lang="ja" dir="ltr">
<head>
<title>sample1150(ImageMagick6.5.2)</title>
</head>
<body>
<?php
/* メッセージ(UTF-8でファイルを保存する) */
$msg = "ImageMagick";
/* 上下余白 */
$padtop = 10;
$padbottom = 40;
/* 看板余白 */
$padx = 5;
$pady = 10;
/* 棒の幅 */
$polew = 10;
/* 塗りつぶし色 */
$fc = "#7799ff";
/* 文字色 */
$tc = "white";

$im = new Imagick();
$idraw = new ImagickDraw();
/* フォント設定 */
//$idraw->setFont('C:\\Windows\\Fonts\\MSGOTHIC.TTC');
$idraw->setFont('Tahoma');
/* フォントサイズ設定 */
$idraw->setFontSize(30);
/* 文字列のサイズ取得 */
$metrics = $im->queryFontMetrics($idraw, $msg);
$tw = $metrics["textWidth"];
$th = $metrics["textHeight"];
$td = $metrics["descender"];

$im->newPseudoImage(
$tw+$padx*2,
$th+$pady*2+$padtop+$padbottom, "xc:none");
/* 看板 */
$idraw->setFillColor($fc);
$idraw->rectangle(0,$padtop,
$tw+$padx*2-1,
$padtop+$th+$pady*2-1);
$idraw->setStrokeColor($fc);
$idraw->setStrokeWidth($polew);
$idraw->rectangle(($tw+$padx*2)/2,0,
($tw+$padx*2)/2,
$padtop+$th+$pady*2+$padbottom);
$idraw->setFillColor($tc);
$idraw->setStrokeColor($tc);
$idraw->setStrokeWidth(0);
$idraw->annotation($padx, $padtop+$pady+$th+$td, $msg);
$im->drawImage($idraw);


$im->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
$im->setImageMatte(true);
$args2 = array($im->getImageWidth()/2,
$im->getImageHeight(),1,rand(-3,3));
//$im->distortImage(Imagick::DISTORTION_SCALEROTATETRANSLATE,
// $args2, false);
// ScaleRotateTranslateDistortion in distort.h
$im->distortImage(3, $args2, true);

$im->writeImage('sample1150a.png');

$idraw->destroy();
$im->destroy();
?>
<img src="sample1150a.png" /><br />

</body>
</html>


出力画像(sample1150a.png)
Imagickで描画した看板

No comments: