2013-05-08 65 views
2

關於如何創建APNG圖像(動畫PNG)有很多解決方案,但是如何將APNG圖像幀分割爲單獨的圖像?如何將動畫PNG與PHP分開?

在此先感謝。

+1

您可以用'exec'或類似的功能呢? – 2013-05-08 08:31:57

+0

不幸的是,不能使用exec。但感謝您的替代解決方案:) – 2013-05-08 09:49:55

回答

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

真棒...工作像一個魅力。謝謝你SOOOOO很多 – 2013-05-08 09:49:15

+0

嗨!我只注意到腳本結果中的錯誤。出於某種原因,只有第一幀是有效的,其他人在圖像中有一些錯誤。因爲這個錯誤的圖像在PHP和Firefox瀏覽器中無效。你有什麼想法,爲什麼? – 2013-09-11 09:29:38