[code]<?php
	set_time_limit(0);
	header("Content-type: image/jpeg");
	
	function replacebg ($bg, $picture, $replacement) {
		$im_picture = imagecreatefromjpeg($picture);		
		$im_bg = imagecreatefromjpeg($bg);
		$im_replacement = imagecreatefromjpeg($replacement);		
		$new_image = imagecreatetruecolor(1600, 1200);
  
		for ($y = 0; $y < 1200; $y++) {
			for ($x = 0; $x < 1600; $x++) {				
				if (imagecolorat($im_bg, $x, $y) == imagecolorat($im_picture, $x, $y)) {
					$color = imagecolorat($im_replacement, $x, $y);
				} else {
					$color = imagecolorat($im_picture, $x, $y);
				}
				//echo $color;
				$r = ($color >> 16) & 0xFF;
				$g = ($color >> 8) & 0xFF;
				$b = $color & 0xFF;
				$clr = imagecolorallocate($new_image, $r, $g, $b);
				imagesetpixel($new_image, $x, $y, $clr);
			}
		}
		$im_picture = '';
		$im_bg = '';
		$im_replacement = '';
		imagejpeg($new_image, NULL, 100);
		imagedestroy($new_image);
	}
	
	replacebg ('bg.jpg', 'picture.jpg', 'replacement.jpg');[/code]