How to delete transparent color in images?

Qiao picture Qiao · Aug 21, 2010 · Viewed 6.9k times · Source

What is the best way to replace transparent colors with white in gif and png images with php?

// get transparent color indexes
$trsp = ImageColorsForIndex($image, ImageColorTransparent($image));
// get transparent color set
$delete = imagecolorallocate($image, $trsp['red'], $trsp['green'], $trsp['blue']); 
// replace
imagecolorset($image, $delete, 255, 255, 255);

does not working.

Answer

Mike picture Mike · Aug 21, 2010

I don't really use GD all that much - I prefer ImageMagick. The following method works, but I'm not sure if it is the most efficient:

// Get the original image.
$src = imagecreatefrompng('trans.png');

// Get the width and height.
$width = imagesx($src);
$height = imagesy($src);

// Create a white background, the same size as the original.
$bg = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($bg, 255, 255, 255);
imagefill($bg, 0, 0, $white);

// Merge the two images.
imagecopyresampled(
    $bg, $src,
    0, 0, 0, 0,
    $width, $height,
    $width, $height);

// Save the finished image.
imagepng($bg, 'merged.png', 0);