define('src_name', 'input.jpg');	
define('dest_name', 'output.jpg');	

$img = imagecreatefromjpeg(src_name);	

if(empty($img)){
	echo 'Image could not be loaded!'; 
	exit; 
}

$black = imagecolorallocate($img, 0, 0, 0);
$white = imagecolorallocate($img, 255, 255, 255);
$width = imagesx($img);
$height = imagesy($img);

$array_lum = array(); 	
$sum_lum = 0;		
$average_lum = 0;	

for($x = 0; $x < $width; $x++){	
	for($y = 0; $y < $height; $y++){
		
		$color = imagecolorat($img, $x, $y);
		$r = ($color >> 16) & 0xFF;
		$g = ($color >> 8) & 0xFF;
		$b = $color & 0xFF;
		
		$array_lum[$x][$y] = ($r + $g + $b);
		
		$sum_lum += $array_lum[$x][$y];
	}
}


$average_lum = $sum_lum / ($width * $height);

for($x = 0; $x < $width; $x++){	
	for($y = 0; $y < $height; $y++){
		
		
		if($array_lum[$x][$y] > $average_lum){
			imagesetpixel($img, $x, $y, $white);
		}
		else{
			imagesetpixel($img, $x, $y, $black);
		}
	}
}

imagejpeg($img, dest_name);

if(!file_exists(dest_name)){
	echo 'Image not saved! Check permission!';
}