Question

I am working on a script which will convert jpg to gif. The problem I am facing is that the output of imagegif is with bad quality and some colors change. ( black )

Here are to samples. One in JPG and the other in GIF.

http://oi62.tinypic.com/atx1j.jpg [JPG] http://oi62.tinypic.com/oiyscy.jpg [GIF]

As you can see the colors of the GIF image has changed alitle.

I am using the following code

$img = imagecreatefromstring(base64_decode($image));
imagegif($img, "output.gif");

How can I improve the quality of the gif image?

Was it helpful?

Solution

Here's how you could achieve slightly better quality:

<?php

// load image
$image = imagecreatefromstring(file_get_contents('http://oi62.tinypic.com/atx1j.jpg'));

// create a true color image of the same size
$image2 = imagecreatetruecolor(imagesx($image), imagesy($image));

// copy the original gif image on to the true color image
imagecopy($image2, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));

// output image
header("Content-Type: image/gif");
imagegif($image2);
imagedestroy($image);
imagedestroy($image2);

?>

Source Image

enter image description here

PHP Generated GIF Image

enter image description here

As you can see, it's slightly better. Very close to orignal. But you are still limited to 256 colors in GIF =[

OTHER TIPS

GIF is inherently worse in quality than JPEG, this is because GIF only has 256 colours available to use, while JPEG has 4,294,967,296 colours...

If you have fewer than 256 colours in your image, GIF is actually higher quality than JPEG, since it doesn't do any compression, while jpeg compresses.

This has nothing to do with PHP: The JPEG format is a true color (or grayscale) format, while the GIF format is a palette format, with max palette size way below true color.

You need to reconsider your conversion process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top