Saturday, January 10, 2009

ImageMagickとPHPで画像の左右をギザギザに切り取る

ImageMagickとPHPで画像の左右をギザギザに切り取るには、以下のコードを実行します。

<!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>sample736(ImageMagick6.4.4)</title>
</head>
<body>
<?php
/* 画像の左右をぎざぎざに切り取る */
$im = new Imagick("sf.jpg");

/* 左右がぎざぎざになったマスクを作成 */
$im2 = new Imagick();
$im2->newImage($im->getImageWidth(), 10, "none");
$im2->setImageMatte(true);
$idraw = new ImagickDraw();
$idraw->pushPattern('mask', 0, 0, $im->getImageWidth(), 10);
$idraw->setFillColor('white');
$points[] = array('x' => 0, 'y' => 0);
$points[] = array('x' => 5, 'y' => 5);
$points[] = array('x' => 1, 'y' => 9);
$points[] = array('x' => $im->getImageWidth()-1, 'y' => 9);
$points[] = array('x' => $im->getImageWidth()-1-5, 'y' => 5);
$points[] = array('x' => $im->getImageWidth()-1, 'y' => 0);
$idraw->polygon($points);
$idraw->popPattern();
$idraw->setFillPatternUrl('#mask');
$idraw->rectangle(0, 0, $im->getImageWidth(), $im->getImageHeight());

$im3 = new Imagick();
$im3->newImage($im->getImageWidth(), $im->getImageHeight(), "none");
$im3->setImageMatte(true);
$im3->drawImage($idraw);

/* マスクで画像を切り取り */
$im3->compositeImage($im, Imagick::COMPOSITE_IN, 0, 0, Imagick::CHANNEL_ALL);

$im3->writeImage('sample736a.png');

$idraw->destroy();
$im3->destroy();
$im2->destroy();
$im->destroy();
?>
<img src="sample736a.png" />

</body>
</html>

元画像(sf.jpg)


出力画像(sample736a.png)

No comments: