2013-05-08 1 views
2

APNG 이미지 (애니메이션 PNG)를 만드는 방법에 대한 많은 해결책이 있지만 어떻게 APNG 이미지 프레임을 별도의 이미지로 나눌 수 있습니까?PHP로 애니메이션 PNG를 어떻게 분할 할 수 있습니까?

미리 감사드립니다.

+1

당신이'exec' 또는 유사한 기능을 사용할 수 있습니까? –

+0

아니요. 불행히도 exec를 사용할 수 없습니다. 하지만 대체 솔루션 덕분에 :) –

답변

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

awesome ... 매력처럼 일했습니다. 감사합니다. –

+0

안녕하세요! 방금 스크립트 결과에 오류가 있음을 알았습니다. 어떤 이유로 첫 번째 프레임 만 유효합니다. 다른 이미지에 약간의 오류가 있습니다. 그 때문에 오류가있는 이미지는 PHP 및 Firefox 브라우저에서 유효하지 않습니다. 왜 그런지 알고 있니? –

관련 문제