【问题标题】:How can I split animated PNG with PHP?如何用 PHP 分割动画 PNG?
【发布时间】:2013-05-02 09:24:42
【问题描述】:

关于如何创建 APNG 图像(动画 PNG)有很多解决方案,但是如何将 APNG 图像帧拆分为单独的图像?

提前致谢。

【问题讨论】:

  • 可以使用exec或类似功能吗?
  • 没有。不幸的是不能使用 exec。但是感谢您提供替代解决方案:)

标签: php animation png apng


【解决方案1】:

这里有一些示例代码,它将采用字节数组形式的 png,并将各种帧作为字节数组的数组返回。

function splitapng($data) {
  $parts = array();

  // Save the PNG signature   
  $signature = substr($data, 0, 8);
  $offset = 8;
  $size = strlen($data);
  while ($offset < $size) {
    // Read the chunk length
    $length = substr($data, $offset, 4);
    $offset += 4;

    // Read the chunk type
    $type = substr($data, $offset, 4);
    $offset += 4;

    // Unpack the length and read the chunk data including 4 byte CRC
    $ilength = unpack('Nlength', $length);
    $ilength = $ilength['length'];
    $chunk = substr($data, $offset, $ilength+4); 
    $offset += $ilength+4;

    if ($type == 'IHDR')
      $header = $length . $type . $chunk;  // save the header chunk
    else if ($type == 'IEND')
      $end = $length . $type . $chunk;     // save the end chunk
    else if ($type == 'IDAT') 
      $parts[] = $length . $type . $chunk; // save the first frame
    else if ($type == 'fdAT') {
      // Animation frames need a bit of tweaking.
      // We need to drop the first 4 bytes and set the correct type.
      $length = pack('N', $ilength-4);
      $type = 'IDAT';
      $chunk = substr($chunk,4);
      $parts[] = $length . $type . $chunk;
    }
  }

  // Now we just add the signature, header, and end chunks to every part.
  for ($i = 0; $i < count($parts); $i++) {
    $parts[$i] = $signature . $header . $parts[$i] . $end;
  }

  return $parts;
}

一个示例调用,加载文件并保存部分:

$filename = 'example.png';

$handle = fopen($filename, 'rb');
$filesize = filesize($filename);
$data = fread($handle, $filesize);
fclose($handle);

$parts = splitapng($data);

for ($i = 0; $i < count($parts); $i++) {
  $handle = fopen("part-$i.png",'wb');
  fwrite($handle,$parts[$i]);
  fclose($handle);
}

【讨论】:

  • 嗨!我刚刚注意到脚本结果中有一个错误。由于某种原因,只有第一帧是有效的,其他的图像中有一些错误。因此,带有错误的图像在 PHP 和 Firefox 浏览器中无效。你知道为什么吗?
【解决方案2】:

splitapng()(错误的 crc32)中存在一个小错误,它会生成损坏的 png 图像...已修复:https://stackoverflow.com/a/61241937/13317744

【讨论】:

  • 请发表详细的答案,然后参考。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
  • 2012-12-10
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多