我正在尝试通过从文件中读取字符并相应地设置像素来生成图像。如果我输入表示例如数据的数据,一切正常50 x 50像素的图像。但如果我输入更大的东西,例如200 x 200使用错误的颜色来填充土地!
小例子:
50x50 Data pastebin
大例子:
200x200 Data pastebin
和代码:
<?php
$scale=2;
$file = file_get_contents('data');
$rows = explode("\n", $file);
$land = "x"; $water="o";
$width=0;
$height=count($rows);
$index=0;
foreach($rows as $row){
$rows[$index] = preg_split('//', $rows[$index]);
$index++;
$width=$index;
}
$img = imagecreatetruecolor($width,$height);
$color1 = imagecolorallocate($img, 139,69,19);
$color2 = imagecolorallocate($img, 10,25,255);
for($i=0;$i<count($rows);$i++){
$x=-1;
$y=$i;
foreach($rows[$i] as $key => $char){
$landMultiplier = 1;
$waterMultiplier=1;
switch ($char){
case $land:
if($rows[$i][$key-1]==$water || $rows[$i][$key+1]==$water || $rows[$i-1][$key]==$water ){
$landMultiplier = -20;
}elseif($rows[$i][$key-2]==$water || $rows[$i][$key+2]==$water || $rows[$i-2][$key]==$water ){
$landMultiplier = -10;
}
$r = max(0,min(255,rand(130,139) + $landMultiplier));
$g = max(0,min(255,rand(60,69) + $landMultiplier));
$b = max(0,min(255,rand(10,19) + $landMultiplier));
$color1 = imagecolorallocate($img,$r ,$g,$b);
imagesetpixel($img,$x,$y,$color1);
break;
case $water:
$color2 = imagecolorallocate($img, rand(0,10),rand(0,25),255);
imagesetpixel($img,$x,$y,$color2);
break;
}
$x++;
}
}
$new_img = imagecreate($scale * $width,$scale * $height);
imagecopyresized($new_img,$img,0,0,0,0,$scale * $width,$scale * $height,$width,$height);
header('Content-Type: image/png');
imagepng($new_img);
?>