애니메이션을 파괴하지 않고 애니메이션 GIF 파일을 크기를 조정하십시오

StackOverflow https://stackoverflow.com/questions/718491

문제

애니메이션을 파괴하지 않고 애니메이션 GIF 파일을 크기를 조정해야합니다.

PHP를 사용하여 어떻게해야합니까?

도움이 되었습니까?

해결책

imagemagick 액세스 권한이 있다면 다음을 수행 할 수 있습니다.

system("convert big.gif -coalesce coalesce.gif");
system("convert -size 200x100 coalesce.gif -resize 200x10 small.gif");

System () 액세스가없는 경우 imageMagick 플러그인에서 가능할 가능성이 높습니다.

참고 : 이는 이미지를 본질적으로 탈취하여 더 작은 크기의 이미지를 만들지 만 더 큰 파일 크기를 생성 할 수 있습니다.

업데이트:imageMagick 액세스 권한이없는 경우 다음 단계의 조합을 사용하여 애니메이션 GIF 크기를 조정할 수 있어야합니다 (GD 액세스 권한이 있다고 가정).

  1. 이미지가 애니메이션 GIF인지 감지하십시오. PHP 및 GD를 사용하여 애니메이션 GIF를 감지 할 수 있습니까? (최고 답변)
  2. 애니메이션 GIF를 개별 프레임으로 나눕니다. http://www.phpclasses.org/package/3234-php-split-gif-animations-into-multiple-images.html
  3. 개별 프레임 크기 조정 : http://www.akemapa.com/2008/07/10/php-gd-resize-transparent-image-png-gif/
  4. 프레임을 애니메이션 GIF로 다시 조정하십시오. http://www.phpclasses.org/package/3163-php-generate-gif-animations-from-a-set-of-gif-images.html

이것은 Imagemagick 경로보다 훨씬 더 집중적이지만 기술적으로 가능해야합니다.

작동한다면 세상과 공유하십시오!

다른 팁

노력하다 Gdenhancer (사용 imagecraft). GD 라이브러리 만 필요하며 GIF 애니메이션을 유지합니다.

GIF를 프레임, 썸네일 및 재 조립으로 분해해야합니다.

살펴보십시오 Imagemagick 그리고 이 튜토리얼.

예제 http://www.php.net/manual/en/imagick.coalesceimages.php 프레임 타이밍을 유지하면서 GIF 크기를 조정합니다. 대부분의 다른 예는하지 않습니다.

다른 예 재건 GIF는 당신이 허용합니다 수정하다 이미지의 프레임.

나는 Imagick PHP 모듈로 애니메이션 GIF를 크기를 조정하는 수많은 예를 시도했지만 그중 어느 것도 저에게 도움이되지 않았습니다. 그런 다음 마침내 디버깅 시간이 끝난 후 실제 문제를 발견했습니다. 이미지를 디스크에 저장하면 애니메이션이 손실되었습니다. $animation->writeImage($file_dst); 또는$animation->writeImages($file_dst, true);

나는 그것을 변경했다file_put_contents($file_dst, $animation->getImagesBlob());그리고 대부분의 예는 즉시 작동하기 시작했습니다.

그것이 누군가를 돕기를 바랍니다.

imageMagick이 설치된 경우 한 번의 전화를 사용할 수 있습니다. convert:

system("convert big.gif -coalesce -repage 0x0 -resize 200x100 -layers Optimize small.gif");

나는 이것을 가방에 넣었다 고 생각합니다.

이 솔루션은 결코 완벽하지 않으며 여기저기서 약간의 무차별적인 힘을 포함하지만 GD / PHP 기반 이미지 크기 조정 스크립트를 애니메이션을 지원하기에 충분한 기능으로 추가 할 수있었습니다.

이 솔루션은 László Zsidi의 우수한 프리웨어 라이브러리를 기반으로합니다. http://www.phpclasses.org/browse/author/283569.html

빠른 데모를 확인하고 소스를 다운로드 할 수 있습니다. http://forssto.com/gifexample/ (직접 링크 : http://forssto.com/gifexample/gifanimresize.zip )

알려진 문제 :

  • 투명성 지원 -이 솔루션에 쉽게 추가하기가 쉽지만 즉각적인 필요가 없으므로 여기서 멈추고 있습니다.

  • 프레임 속도 - 알려지지 않은 이유에 대해 GifenCoder 클래스가 지정된 프레임 속도를 고려하지 않습니다. 나중에 이것을 살펴볼 필요가 있습니다.

  • 테스트 세트에서 하나의 GIF 파일을 찾았으며 어떻게 든 크기가 다른 프레임이 있고 애니메이션이 올바르게 작동하지 않았습니다. 그럼에도 불구하고 여전히 디버깅.

단지 3 폴더 이름을 작성하십시오 1.frame_output 2.Images 3.Resize_frame_output 및 아래 에서이 링크에서 2 인 코더 및 디코더 클래스를 다운로드하십시오. http://phpclasses.elib.com/browse/package/3234.html 2. 클래스 "gifencoder.class.php"에서 클래스를 다운로드합니다 http://phpclasses.betablue.net/browse/package/3163.html

그런 다음 스크립트 이름을 "resize_animator.php"로 실행하고 업로드 HTML 파일을 생성하고 스크립트를 즐기십시오.

..이 스크립트를 ..... index.php로 작성합니다 .......

<html>
<body>
<table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form action="resize_animator.php" method="post" enctype="multipart/form-data" >
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td align="center"><font face="Tahoma">SELECT ANIMATED FILE</font> 
<input type="file" name="uploadfile" size="20" accept="image/gif"/>
</td>
</tr>
<tr>
<td align="center"><input type="submit" name="Submit" value="PROCESS ANIMATION" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
</body>
</html>

........................ resire_animator.php로 저장 하고이 스크립트를 저장하고 ............

   <?php

   require "GIFDecoder.class.php";
   include "GIFEncoder.class.php";
   $file_name= $_FILES['uploadfile']['name'];
   $file_ext = substr($file_name, -4);
   $file_size=($_FILES["uploadfile"]["size"] /1024 );
   if($file_ext=='.gif')
    {
 if($file_size > 0 && $file_size < 2000 )
  {
    session_start ( );
        $uploaded_file = $_FILES['uploadfile']['tmp_name'];
        $fp=file_get_contents($uploaded_file);

        if ( $fp )
            {
                $_SESSION['delays'] = Array ( );
                $gif = new GIFDecoder ( $fp );
                $arr = $gif->GIFGetFrames ( );
                $_SESSION [ 'delays' ] = $gif -> GIFGetDelays ( );

                for ( $i = 0; $i < count ( $arr ); $i++ )
                {
                        fwrite ( fopen ( ( $i < 10 ? "frame_output/$i$i_frame.gif" : "frame_output/$i_frame.gif" ), "wb" ), $arr [ $i ] );
                }
          }

        function resize_frames($newwidth,$newheight)
            {
                    $dir=opendir("frame_output/");
                    $i=0;
                    while($imgfile=readdir($dir))
                    {
                         if ($imgfile != "." && $imgfile!="..")
                             {
                                        $imgarray[$i]=$imgfile;
                                        $uploadedfile = "frame_output/".$imgarray[$i];
                                        $src = imagecreatefromgif($uploadedfile);
                                        list($width,$height)=getimagesize($uploadedfile);
                                        $tmp=imagecreatetruecolor($newwidth,$newheight);
                                        imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
                                        $filename = "resized_frame_output/".$imgarray[$i];
                                        imagegif($tmp,$filename,100);
                                        imagedestroy($src);
                                        imagedestroy($tmp);
                                        $i++;
                            }
                    }
                    closedir($dir);

                if ( $dh = opendir ( "resized_frame_output/" ) )
                {
                    while ( false !== ( $dat = readdir ( $dh ) ) )
                    {
                        if ( $dat != "." && $dat != ".." )
                        {
                            $frames [ ] = "resized_frame_output/$dat";
                        }
                    }
                    closedir ( $dh );
                }

            $gif = new GIFEncoder   ( $frames,$_SESSION [ 'delays' ],0, 2, 0, 0, 0,"url" );
            $data = $gif->GetAnimation ( );

            $x='x';
            $y='_';
            $uploaded_file_name= $_FILES['uploadfile']['name'];
            $actual_file_name = substr($uploaded_file_name, 0, -4);
            $file_extention = substr($uploaded_file_name, -4);
            $new_name=$actual_file_name.$y.$newwidth.$x.$newheight.$file_extention ;

            //$output_image_name=$newwidth.$x.$newheight;
            fwrite ( fopen ( "images/$new_name", "wb" ), $data );
            //remove resized frames from folder
            //sleep for 1 second
            // usleep(2000000);
            $dir = 'resized_frame_output/';
            foreach(glob($dir.'*.*') as $v)
                {
                 unlink($v);
                }
        }  // end of function resize_frames


            $gif = new GIFEncoder   ( $frames,$_SESSION [ 'delays' ],0, 2, 0, 0, 0,"url" );
            $data = $gif->GetAnimation ( );

            $x='x';
            $y='_';
            $z='_p';
            $uploaded_file_name= $_FILES['uploadfile']['name'];
            $actual_file_name = substr($uploaded_file_name, 0, -4);
            $file_extention = substr($uploaded_file_name, -4);
            $new_name=$actual_file_name.$y.$newwidth.$x.$newheight.$z.$file_extention ;

            //$output_image_name=$newwidth.$x.$newheight;
            fwrite ( fopen ( "images/$new_name", "wb" ), $data );
            //remove resized frames from folder
            //sleep for 1 second
             //usleep(2000000);
            $dir = 'resized_frame_output/';
            foreach(glob($dir.'*.*') as $v)
                {
                 unlink($v);
                }
        }  // end of function resize_frames

            resize_frames(110,110);
            resize_frames(120,160);
            resize_frames(120,80);
            resize_frames(128,96);
            resize_frames(128,128);
            resize_frames(208,208);
            resize_frames(208,320);

            session_destroy();

            //usleep(200000);

            //remove resized frames from folder
            $dir = 'frame_output/';
            foreach(glob($dir.'*.*') as $v)
                {
                 unlink($v);
                }
      echo "<center><h1>Your Animation processing is compleated.</h1></center>";
      echo "<center><h2><a href=\"index.php\">BACK TO UPLOAD PAGE</h2></center>";
  }  //end of file size checker
else
 {
      echo "<center><h2>You Upload a unfit size image .Upload a file within 2000 KB</h2></center>";
      echo "<center><h2><a href=\"index.php\">BACK TO UPLOAD PAGE</h2></center>";
 }
   } //end of file extention checker
  else
  {
   echo "<center><h2>Uplaod a gif file!</h2></center>";
   echo "<center><h2><a href=\"index.php\">BACK TO UPLOAD PAGE</h2></center>";
  }
  ?>

.......................즐기자............

usleep 함수는 그 폴더에서 작업이 발생하는 것을 보려면 수면 기능이 필요하지는 않지만 기능을보기 위해 사용합니다.

서버에 imagemagick이 없다면 이것을 시도 할 수 있습니다.

http://www.phpclasses.org/package/7353-php-resize-animations-in-files-of-gif-format.html

이 클래스는 GD로 GIF 애니메이션을 크기를 조정하고 있습니다. 먼저 프레임을 구문 분석 한 다음 크기를 조정 한 후 지연 시간, 폐기 방법, 색상 테이블 등을 잃지 않고 단일 파일로 다시 컴파일합니다.

버그를 찾거나 최적화 등을 제안하려면 클래스 포럼을 사용하거나 내 웹 사이트의 페이지에 댓글을 남길 수 있습니다. 그리고 최대한 빨리 대답하겠습니다.

Trough Imagemagick을 제외한이 모든 대답은 나를 위해 효과가 없었습니다. 이 전에 답의 스크립트는 모두 오류로 가득 차 있습니다.

Imagemagick을 설치하는조차도 관리하기가 어려웠으므로 여기에 내 경험이 있습니다.

여기에 있습니다 imagemagick을 설치하는 방법 Windows 7 및 XAMPP에서 1.7.4.
메모: 64 비트 (Win7 용)를 선택하고 설치할 때 휴가를 확인하면 "시스템 경로 추가"옵션이 확인되었습니다.

다음을 따르십시오.http://www.creativearmory.com/tutorials/resize-animated-gifs-with-php-and-imagemagick

이 게시물에서 스크립트에서 몇 시간을 잃었고 Imagemagick 과이 튜토리얼은 몇 분 안에 성공했습니다.

그리고 한 가지 더 참고 : 내 웹 서버에는 기본적으로 imageMagick이 있으므로 대부분의 서버도 있다고 생각합니다.

gif 애니메이션 레기 라이저 트릭을 수행 할 간단한 일급 도구입니다.

메모: 임시 폴더를 사용하여 별도의 프레임을 작성합니다. 프레임을 타임 스탬프하는 동안 여러 사용자가 동시에 GIF를 크기를 조정하는 서버 에서이를 사용하려면 고유 한 폴더를 만들어야 할 수도 있습니다.

imagecraft 신뢰할 수있는 PHP GD 라이브러리 및 확장자이며 GIF 애니메이션을 유지하고 여러 레이어로 이미지를 편집 및 구성하고 워터 마크를 지원합니다.

이 기능을 사용했습니다.

function gifResize($file_origin,$file_dest,$percent){       
   $crop_w = 0;
   $crop_h = 0;
   $crop_x = 0;
   $crop_y = 0;
   $image = new Imagick($file_origin);
   $originalWidth = $image->getImageWidth();
   $originalHeight = $image->getImageHeight();
   $size_w = ($originalWidth*$percent)/100;
   $size_h = ($originalHeight*$percent)/100;
   if(($size_w-$originalWidth)>($size_h-$originalHeight)){
       $s = $size_h/$originalHeight;
       $size_w = round($originalWidth*$s);
       $size_h = round($originalHeight*$s);
   }else{
       $s = $size_w/$originalWidth;
       $size_w = round($originalWidth*$s);
       $size_h = round($originalHeight*$s);
   }       
   $image = $image->coalesceImages();

   foreach ($image as $frame) {
       $frame->cropImage($crop_w, $crop_h, $crop_x, $crop_y);
       $frame->thumbnailImage($size_h, $size_w);
       $frame->setImagePage($size_h, $size_w, 0, 0);
   }
   $imageContent = $image->getImagesBlob();
   $fp = fopen($file_dest,'w');
   fwrite($fp,$imageContent);
   fclose($fp);

}

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top