How to remove background of a image and copy into another?

Posted by Gustavo Pinent on Stack Overflow See other posts from Stack Overflow or by Gustavo Pinent
Published on 2014-06-09T03:22:30Z Indexed on 2014/06/09 3:24 UTC
Read the original article Hit count: 125

Filed under:
|
|

I'm researching about captchas. In this idea, the task is: create a image from a JPEG and remove the white background, than create another image from another JPEG, than create the final image by adding the second as a background, and copying the first one over this background preserving the transparent area created, of course. Here is the code:

header("Content-Type: image/jpeg");

$nFundo = rand(0,4);
$Dirs = array(rand(0,7), rand(0,7), rand(0,7), rand(0,7)); // Will be four times all

$_SESSION["form_captcha"] = $Dirs;

$image = ImageCreatetruecolor(320, 80);
ImageAlphaBlending($image, FALSE);
ImageSaveAlpha($image, TRUE);

$image_seta = ImageCreateFromJPEG("_captcha-seta.jpg"); // Image do copy over
$image_fundo = ImageCreateFromJPEG("_captcha-fundo-".$nFundo.".jpg"); // Image to make the background

for($i=0; $i<4; $i++){
    ImageCopy($image, $image_fundo, $i*80, 0, 0, 0, 80, 80);
}
// So far so good, a background with a pattern repeated four times
$color_white = ImageColorAllocate($image_seta, 255, 255, 255);
ImageColorTransparent($image_seta, $color_white);
ImageSaveAlpha($image_seta, TRUE);

for($i=0; $i<4; $i++){
    $image_seta_rot = imageRotate($image_seta, $Dirs[$i]*45, $color_white);
    ImageCopyResampled($image, $image_seta_rot, $i*80, 0, 0, 0, 80, 80, 80, 80); // Try
}

echo(imagejpeg($image));

imagedestroy($image);

I tried to replace $image_seta_rot by $image_seta ("Try" line) to see if the rotation is the problem, but even without rotation, the white wasn't removed and the image just "erase" the background created before. So the copy is failing or the white were never removed... I may create a PNG with transparent background, but will be interesting to learn how to make it dynamically, don't you think? Any ideas?

© Stack Overflow or respective owner

Related posts about php

Related posts about image-processing