I m trying to remove the background of an image and make it transparent using PHP without using any 3rd party plugins like ImageMagick or another.
I came across this code in SO itself which promised to echo out transparent background image as result. After trying it did work but I had to define every color in RGB that need to be removed. This is a huge setback as the background colors may vary from image to image as I upload.
The code I tried:
<?php
$_filename='https://vdofy.harryatwork.com/dev/images-main/images/16330699786156ab99b0c44.png';
$_backgroundColour='0,0,0';
$_img = imagecreatefrompng($_filename);
$_backgroundColours = explode(',', $_backgroundColour);
$_removeColour = imagecolorallocate($_img, (int)$_backgroundColours[0], (int)$_backgroundColours[1], (int)$_backgroundColours[2]);
imagecolortransparent($_img, $_removeColour);
imagesavealpha($_img, true);
$_transColor = imagecolorallocatealpha($_img, 0, 0, 0, 127);
imagefill($_img, 0, 0, $_transColor);
imagepng($_img, $_SERVER['DOCUMENT_ROOT']."/bg_removed.png");
?>
Can you guys please share your expertise on making this work?