Fen2Png

1 minute read

Generating board images from a given FEN string can be useful for documenting games so I hacked together a small script that does this. It’s not pixel perfect but gets the job done.

Here is how to use it

http://deniz.dizman.org/ext/fen2png/?fen=<FEN_POSITION>

$fen = $_GET['fen'];
if (!isset($fen)) {
  http_response_code(501);
  return;
}
$square = 0;
$arr = array();
$len = strlen($fen);
for($i=0;$i<$len;$i++) {
  $char = $fen[$i];
  if($char == '/') {
    //$square+=8;
  } else if (is_numeric($char)) {
    $square += $char;
  } else {
    $arr[$square] = $char;
    $square++;
  }
}

$board = imagecreatefrompng("xboard.png");
$pcs = array(
  "K"=>imagecreatefrompng("wK.png"),
  "Q"=>imagecreatefrompng("wQ.png"),
  "B"=>imagecreatefrompng("wB.png"),
  "N"=>imagecreatefrompng("wN.png"),
  "R"=>imagecreatefrompng("wR.png"),
  "P"=>imagecreatefrompng("wP.png"),
  "k"=>imagecreatefrompng("bK.png"),
  "q"=>imagecreatefrompng("bQ.png"),
  "b"=>imagecreatefrompng("bB.png"),
  "n"=>imagecreatefrompng("bN.png"),
  "r"=>imagecreatefrompng("bR.png"),
  "p"=>imagecreatefrompng("bP.png")
);


$output = uniqid().".png";
for($i=0;$i<64;$i++) {
  if (!isset($arr[$i])) continue;
  $srcimg = $pcs[$arr[$i]];
  imagecopy($board, $srcimg, 49 * ($i % 8), 49 * intdiv($i, 8), 0, 0, 50, 50);
}
imagepng($board, $output, 9);

foreach($pcs as $k=>$v) {
  imagedestroy($pcs[$k]);
}
imagedestroy($board);

header("Content-type: image/png");
header("Content-size: " . filesize($output));
readfile($output);