Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete transparent color in images?

Tags:

php

image

gd

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.

like image 663
Qiao Avatar asked Aug 21 '10 15:08

Qiao


1 Answers

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);
like image 109
Mike Avatar answered Oct 07 '22 02:10

Mike