Skip to content

Instantly share code, notes, and snippets.

@nandakoryaaa
Last active March 22, 2023 21:41
Show Gist options
  • Save nandakoryaaa/8c27343f275149a6f5ccd579d89bba51 to your computer and use it in GitHub Desktop.
Save nandakoryaaa/8c27343f275149a6f5ccd579d89bba51 to your computer and use it in GitHub Desktop.
convert raster font image to array of bitmask bytes
<?php
$infile = $argv[1]; // font image file name
$w = $argv[2]; // font char width
$h = $argv[3]; // font char height
$color_x = $argv[4] ?? 0; // x coordinate of font color sample
$color_y = $argv[5] ?? 0; // y coordinate of font color sample
$img = imagecreatefrompng($infile);
$img_w = imagesx($img);
$img_h = imagesy($img);
$color = imagecolorat($img, $color_x, $color_y);
echo "img w: $img_w, h: $img_h\n";
echo "char w: $w, h: $h\n";
echo "color: $color\n";
$chars = [];
for ($pos_y = 0; $pos_y < $img_h; $pos_y += $h) {
for ($pos_x = 0; $pos_x < $img_w; $pos_x += $w) {
for ($span_y = 0; $span_y < $h; $span_y++) {
$byte = 0;
$mask = 1;
for ($span_x = 0; $span_x < $w; $span_x++) {
$c = imagecolorat($img, $pos_x + $span_x, $pos_y + $span_y);
if ($c == $color) {
$byte |= $mask;
}
$mask <<= 1;
if ($mask > 128) {
$chars[] = $byte;
$byte = 0;
$mask = 1;
}
}
if ($mask > 1) {
$chars[] = $byte;
}
}
}
}
$bytes_per_char = ceil($w / 8) * $h;
echo 'total bytes: ' . count($chars) . "\n";
echo "bytes per char: $bytes_per_char\n";
$cnt = 0;
echo "\$chars = [\n";
foreach($chars as $byte) {
if ($cnt == 0) {
echo "\t";
}
echo $byte . ', ';
$cnt++;
if ($cnt == $bytes_per_char) {
echo "\n";
$cnt = 0;
}
}
echo "]\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment