使用PHP将APNG拆分为png图像 [英] Splitting APNG into png images with PHP

查看:261
本文介绍了使用PHP将APNG拆分为png图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个php代码,可将动画PNG图像(APNG)分成帧,但是存在某种错误.该函数创建的图像无效(PHP在PHP imagecreatefrompng()函数中不返回图像资源(在Firefox浏览器中均未显示).

I have a php code that splits an animated PNG image (APNG) into frames, but there is some kind of error. The images that are created by the function are not valid (PHP does not return an image resource in PHP imagecreatefrompng() function (neither it's displayed in Firefox browser).

引用函数,如何使用PHP分割动画PNG? 通过 James Holderness

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

我尝试修改标题,但没有运气.请帮忙!

I tried modifying headers but no luck. Please, help!

推荐答案

当您将数据块名称从fdAT更改为IDAT,并删除4个数据字节以说明新的数据块名称和数据时,需要重新计算CRC.

The CRC needs to be recomputed when you change a chunk name from fdAT to IDAT, and remove 4 data bytes, to account for the new chunk name and data.

这篇关于使用PHP将APNG拆分为png图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆