Remove Image background with php and save transparent png

后端 未结 7 1244
心在旅途
心在旅途 2020-12-15 01:23

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.

7条回答
  •  隐瞒了意图╮
    2020-12-15 02:24

    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);
    

提交回复
热议问题