Convert background on RGB jpg to be transparent

315 views Asked by At

I know there are bunch of questions for this but none seem to provide actual code to use

I am trying to convert a RGB jpg to convert everything that is

either not black or is white to be transparent

The code I tried using is:

$im = imagecreatefromjpeg($file);
$remove=imagecolorallocatealpha($img, 255,255,255);
imagefill($im,0,0,$remove);
imagesavealpha($im, TRUE);
imagejpeg($im, $trans_file);

but this seems to output the white background as black. Can anyone please help.

Changed my code to use png and same thing happens file looks the same whatever is white converts to black instead of transparent

$im = imagecreatefromjpeg($file);
$remove=imagecolorallocatealpha($img, 255,255,255);
imagefill($im,0,0,$remove);
imagealphablending($im, TRUE);
imagesavealpha($im, TRUE);
imagepng($im, $trans_file);
1

There are 1 answers

1
php_nub_qq On

You can't have transparency in a jpg file. use imagepng($im, $trans_file);, assuming the rest of your code works properly.

EDIT: Not an expert with images but I believe you need to set imagealphablending($image, true); in order to have transparency.