1

How do I create an image without losing all the colors? It is creating an image with speckles and changing the color number doesn't make a difference. The PNG image I start with (uploaded via PHP) is much sharper.

//Create an image from the source
$srcImage = imagecreatefromstring( file_get_contents( $sourcePath ) );

//Get the source width and height
list( $width, $height ) = getimagesize( $sourcePath );

//Create image to paint on
$canvas = imagecreatetruecolor( $width, $height );

//Add alpha for transparency
$bga = imagecolorallocatealpha( $canvas, 0, 0, 0, 127 );
imagecolortransparent( $canvas, $bga );
imagefill( $canvas, 0, 0, $bga );

//Convert to palette (ignores the number of colors)
imagetruecolortopalette( $canvas, true, 1000 );

//Retain transparency
imagesavealpha( $canvas, true );

//Save as PNG to file
imagepng( $canvas, $destPath );

//Remove temporary data
imagedestroy( $canvas );

How do I create a paletted image png with more colors?

Don Rhummy
  • 24,730
  • 42
  • 175
  • 330
  • 1
    a true color image can theoretically have 16.7 million different colors. you're only allowing 1000. Have you checked how many unique r,g,b tuples there are in the original one? If it's >1000, then you're forcing GD to trash your image. – Marc B Oct 04 '13 at 18:15
  • @MarcB I've tried much higher than 1000 and it makes no difference. This also has the same poor quality (and has the same file size: 80.4KB): `imagetruecolortopalette( $canvas, true, 16700000 );` It ignores the color parameter. – Don Rhummy Oct 05 '13 at 19:22
  • @MarcB Any ideas how I could get this working? – Don Rhummy Oct 08 '13 at 16:22
  • why force a palette at all? Just straight save the png without a palette. – Marc B Oct 08 '13 at 16:24
  • 2
    @MarcB because that saves the image as too large (500K). Tinypng is able to shrink the image to 95K and make it indexed without any noticeable loss of quality. I want to do that with PHP. – Don Rhummy Oct 08 '13 at 17:15
  • It would be really nice if the parameter actually worked. This workaround--just transferring to an image object that is not 24-bit true-color--saves size decently without losing quality. Check it out: http://stackoverflow.com/questions/5187480/imagetruecolortopalette-losing-colors – Aaron Gillion Jun 06 '15 at 03:34

0 Answers0