I'm trying to replace a background of an image with a new background.
The input image will be a greenbox image, which should get its green background replaced to transparent, afterwards a new background image should be inserted.
it should go something like that
at the moment im still struggeling at replacing the green pixels with transparent background, as the green pixels rgb-values are changing and not just some static rgb-value.
how could this be archived?
<?php
// rgbs
$red = 44;
$green = 255;
$blue = 56;
$alpha = .45;
// input img
$img = imagecreatefromjpeg('./img.jpg');
// new background
$bg = imagecreatefromjpeg('./bg.jpg');
// replace background
for ($y = 0; $y < imagesy($img); $y++) {
for ($x = 0; $x < imagesx($img); $x++) {
$rgb = imagecolorat($img, $x, $y);
$pixel_color = imagecolorsforindex($img, $rgb);
$oldR = ($pixel_color['red'] - $alpha * $red) / (1 - $alpha);
$oldG = ($pixel_color['green'] - $alpha * $green ) / (1 - $alpha);
$oldB = ($pixel_color['blue'] - $alpha * $blue) / (1 - $alpha);
// replace green with transparent
$color = imagecolorallocate($img, $oldR, $oldG, $oldB);
imagesetpixel($img, $x, $y, $color);
imagecolortransparent($img, $color);
}
}
// save new img
imagesavealpha($img, true);
imagepng($img, './output.png');
?>