对比Imagick和Gmagick的像素迭代功能
通常,图像处理工作都是诸如缩略图,水印之类的简单工作,不过有的时候会复杂些,比如像素迭代,本文通过一个实例对比Imagick和Gmagick的像素迭代功能:
像素数据生成代码
<?php
$data = array();
for ($row = 0; $row < 100; $row++) {
for ($column = 0; $column < 100; $column++) {
$data[$row][$column] = '#' . str_repeat($column % 10, 6);
}
}
?>
Imagick迭代写像素
<?php
require 'data.php';
$image = new Imagick();
$image->newimage(100, 100, 'white', 'png');
$iterator = $image->getPixelIterator();
foreach ($iterator as $row => $pixels) {
foreach ($pixels as $column => $pixel) {
$pixel->setColor($data[$row][$column]);
}
$iterator->syncIterator();
}
$image->writeimage('pixel.png');
?>
注:在Imagick中利用PixelIterator写像素时,需要调用syncIterator操作(读像素不用)。
Gmagick迭代写像素
<?php
require 'data.php';
$image = new Gmagick();
$image->newimage(100, 100, 'white', 'png');
$pixel = new GmagickPixel();
$draw = new GmagickDraw();
for ($row = 0; $row < 100; $row++) {
for ($column = 0; $column < 100; $column++) {
$pixel->setcolor($data[$row][$column]);
$draw->setfillcolor($pixel);
$draw->point($column, $row);
$image->drawimage($draw);
$pixel->clear();
$draw->clear();
}
}
$image->writeimage('pixel.png');
?>
生成的图片如下所示:
pixel.png
前面演示了在迭代时如何写像素,接下来再看看如何读像素(用到了生成的pixel.png):
Imagick迭代读像素
<?php
$data = array();
$image = new Imagick('pixel.png');
$iterator = $image->getpixeliterator();
foreach ($iterator as $row => $pixels) {
foreach ($pixels as $column => $pixel) {
$data[$row][$column] = $pixel->getColor();
}
}
print_r($data);
?>
Gmagick迭代读像素
<?php
$data = array();