在没有GD的情况下加载PNG并在PHP中读取像素?

时间:2009-03-06 22:49:20

标签: php png gd

我需要从真彩色PNG文件中读取确切的未更改像素数据(ARGB),最好是从PHP中读取。

不幸的是,PHP中的GD库与alpha通道混淆(将其从8位减少到7位),使其无法使用。

我目前假设我的选项是:

  1. 实现我自己的原始PNG阅读器以提取必要的数据。
  2. 使用一些破损较少的语言/库,并将其作为shell进程或CGI从PHP中调用。
  3. 我有兴趣听到任何其他想法,或者建议一种方式超越另一种......

    编辑:我认为#1已经出局了。我已经尝试将IDAT数据流传递给gzinflate(),但它只是给我一个数据错误。 (完全相同的事情,使用完全相同的数据,在PHP之外产生预期的结果。)

2 个答案:

答案 0 :(得分:3)

ImageMagick怎么样?

<?php
$im = new Imagick("foo.png");
$it = $im->getPixelIterator();

foreach($it as $row => $pixels) {
    foreach ($pixels as $column => $pixel) {
        // Do something with $pixel
    }

    $it->syncIterator();
}
?>

答案 1 :(得分:0)

您可以使用netpbm的pngtopnm函数将PNG转换为易于解析的PNM。这是一个有点天真的PHP脚本,可以帮助您获得所需:

<?php
$pngFilePath = 'template.png';
// Get the raw results of the png to pnm conversion
$contents = shell_exec("pngtopnm $pngFilePath");
// Break the raw results into lines
//  0: P6
//  1: <WIDTH> <HEIGHT>
//  2: 255
//  3: <BINARY RGB DATA>
$lines = preg_split('/\n/', $contents);

// Ensure that there are exactly 4 lines of data
if(count($lines) != 4)
    die("Unexpected results from pngtopnm.");

// Check that the first line is correct
$type = $lines[0];
if($type != 'P6')
    die("Unexpected pnm file header.");

// Get the width and height (in an array)
$dimensions = preg_split('/ /', $lines[1]);

// Get the data and convert it to an array of RGB bytes
$data = $lines[3];
$bytes = unpack('C*', $data);

print_r($bytes);
?>