代码之家  ›  专栏  ›  技术社区  ›  Miral

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

  •  1
  • Miral  · 技术社区  · 17 年前

    我现在假设我的选择是:

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

    不过,我很有兴趣听听其他的想法,或者是一种方法的建议。。。

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

    2 回复  |  直到 17 年前
        1
  •  3
  •   Can Berk Güder Pugalmuni    17 年前

    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();
    }
    ?>
    
        2
  •  0
  •   PPrice    15 年前

    您可以使用的pngtopnm函数 netpbm

    <?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);
    ?>
    
    推荐文章