【问题标题】:Load PNG and read pixels in PHP without GD?在没有 GD 的情况下在 PHP 中加载 PNG 和读取像素?
【发布时间】:2010-10-11 20:51:44
【问题描述】:

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

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

我目前假设我的选择是:

  1. 实现我自己的原始 PNG 阅读器以提取必要的数据。
  2. 使用一些较少损坏的语言/库,并将其作为 shell 进程或 CGI 从 PHP 中调用。

不过,我很想听听任何其他想法,或者对一种方式优于另一种方式的建议......

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

【问题讨论】:

  • #1 应该出局了。安装 ImageMagick 可能更容易。话虽如此,PNG 比 JPEG 更简单。
  • 实现一个 PNG 阅读器对于你想要用它做的几乎所有事情来说都太慢了。

标签: php png gd


【解决方案1】:

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();
}
?>

【讨论】:

  • 不幸的是,我现在被 PHP4 卡住了,而且 ImageMagick 没有安装在服务器上(看起来也不兼容)。
【解决方案2】:

您可以使用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);
?>

【讨论】:

  • 遗憾的是,这是在托管站点上,所以我无法添加其他软件(如果可以,我会安装 ImageMagick)。碰巧的是,尽管整个事情最终不再被需要,所以它最终变得毫无意义。不过还是谢谢你的回答! (不过,如果那是 RGB 而不是 ARGB,那就没有用了。)
猜你喜欢
  • 1970-01-01
  • 2020-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
  • 2015-11-29
  • 1970-01-01
相关资源
最近更新 更多