I want to remove the white background of any image uploaded on the site working on PHP platform. The uploading function is done but messed up with this functionality.
Version to conversion from URL and return on page:
$img = imagecreatefromjpeg('http://mypage.com/image.jpg');
$remove = imagecolorallocate($img, 255, 255, 255); // Define color rgb to remove
imagecolortransparent($img, $remove);
ob_start();
imagepng($img);
$imgData = ob_get_clean();
imagedestroy($img);
$data_img = 'data:image/png;base64,'.base64_encode($imgData);
echo '<body style="background: #f00;"><img src="'.$data_img.'"></body>';
Use the php image processing and GD, read the image pixel by pixel if the RGB components are all 255 (The pixel is white), set the alpha channel to 255 (transparent). You may have to change the filetype of the image depending if the uploaded filetype supports an alpha channel.
get the index of white color in the image and set it to transparent.
$whiteColorIndex = imagecolorexact($img,255,255,255);
$whiteColor = imagecolorsforindex($img,$whiteColorIndex);
imagecolortransparent($img,$whiteColor);
you can alternatively use imagecolorclosest() if you don't know the exact color.
function transparent_background($filename, $color)
{
$img = imagecreatefrompng('image.png'); //or whatever loading function you need
$colors = explode(',', $color);
$remove = imagecolorallocate($img, $colors[0], $colors[1], $colors[2]);
imagecolortransparent($img, $remove);
imagepng($img, $_SERVER['DOCUMENT_ROOT'].'/'.$filename);
}
transparent_background('logo_100x100.png', '255,255,255');
The function from @geoffs3310 should be the accepted answer here, but note, that the png saved does not contain an alpha channel.
To remove the background and save the new png as a transparent png with alpha the following code works
$_filename='/home/files/IMAGE.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, $_filename);
Since you only need single-color transparency, the easiest way is to define white with imagecolortransparent()
. Something like this (untested code):
$img = imagecreatefromstring($your_image); //or whatever loading function you need
$white = imagecolorallocate($img, 255, 255, 255);
imagecolortransparent($img, $white);
imagepng($img, $output_file_name);