1

I have a script that resizes uploaded images. It works fine for PNGs and JPGs but not GIFs. For the GIFs, it's supposed to convert them into JPGs and then resize them. The conversion works, but then they fail to be resized...

function resize_image($file, $maxWidth, $maxHeight) {
    $jpgFile = substr_replace($file, 'jpeg', -3);
    $fileType = strtolower(substr($file, -3));
    ...
    if ($fileType == 'gif') {
        $test = imagecreatefromgif($file);
        imagejpeg($test, $jpgFile);
        $src = imagecreatefromjpeg($jpgFile);
        $dst = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); 
        imagejpeg($dst, $jpgfile);
    }  
}
Ben Davidow
  • 1,175
  • 5
  • 23
  • 51

3 Answers3

0

I don't think you need to output the image after it's created from a gif - imagecreatefromgif reads an image into memory, you should be able to do this:

$src = imagecreatefromgif($file);
$dst = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); 
imagejpeg($dst, $jpgfile);
scrowler
  • 24,273
  • 9
  • 60
  • 92
0

What version of the GD library are you using? According to the official PHP documentation:

GIF support was removed from the GD library in Version 1.6, and added back in Version 2.0.28. This function is not available between these versions.

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
0

I ended up bypassing the conversion of GIF to JPG, and resized the GIF directly. However, to maintain the transparency (by default it turns the transparent background to black, which is the reason I originally converted it to JPG first before resizing), I had to add in a few instructions.

    $src = imagecreatefromgif($file);
    $dst = imagecreatetruecolor($newWidth, $newHeight);
    imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
    imagealphablending($dst, false);
    imagesavealpha($dst, true);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); 
    imagegif($dst, $file);
Ben Davidow
  • 1,175
  • 5
  • 23
  • 51