问题
I wrote a code that pick all the pixels with a specific color from an image and set them in a blank image. But at a certain amount of pixels imagesetpixel() stops.
Can someone tell me why?
<?php
if(isset($_POST["submit"])){
header("Content-Type: image/png");
$img = imagecreate(200, 100);
imagecolorallocate($img, 0, 0, 0);
$im = imagecreatefrompng("img.png");
$x = imagesx($im);
$y = imagesy($im);
for($i=0; $i<$x; $i++){
for($j=0; $j<$y; $j++){
$rgb = imagecolorsforindex($im, imagecolorat($im, $i, $j));
if($rgb["red"]==$_POST["r1"] && $rgb["green"]==$_POST["g1"] && $rgb["blue"]==$_POST["b1"]){
$s .= "$i,$j ";
imagesetpixel($img, $i, $j, imagecolorallocate($img, $_POST["r1"], $_POST["g1"], $_POST["b1"]));
}
elseif($rgb["red"]==$_POST["r2"] && $rgb["green"]==$_POST["g2"] && $rgb["blue"]==$_POST["b2"]){
$s2 .= "$i,$j ";
//imagesetpixel($img, $i, $j, imagecolorallocate($img, $_POST["r2"], $_POST["g2"], $_POST["b2"]));
}
}
}
imagepng($img);
imagedestroy($img);
//print $s."\n".$s2;
}
else{
print "<center><br /><br /><br /><br /><br /><form method=\"post\" action=\"\">Color 1 : <input type=\"text\" name=\"r1\" size=\"3\" value=\"73\" /><input type=\"text\" name=\"g1\" size=\"3\" value=\"167\" /><input type=\"text\" name=\"b1\" size=\"3\" value=\"248\" /><br />Color 2 : <input type=\"text\" name=\"r2\" size=\"3\" value=\"229\" /><input type=\"text\" name=\"g2\" size=\"3\" value=\"180\" /><input type=\"text\" name=\"b2\" size=\"3\" value=\"253\" /><br /><input type=\"submit\" name=\"submit\" /></form></center>";
}
?>
img.png
回答1:
You are filling up the image's color table.
You allocate a new color every time you paint a pixel, even though they're all the same color.
So do this instead:
$color = imagecolorallocate($img, $_POST["r1"], $_POST["g1"], $_POST["b1"]);
And when you draw a pixel, reuse $color
.
来源:https://stackoverflow.com/questions/7060728/php-imagesetpixel-limits