advent_of_code_2019/day_8/part_2.php

69 lines
1.6 KiB
PHP
Raw Permalink Normal View History

2019-12-09 11:57:44 +01:00
<?php
$input = file_get_contents('input.txt');
const TRANSPARENT = 2;
const WHITE = 1;
const BLACK = 0;
const WIDTH = 25;
const HEIGHT = 6;
$area = WIDTH * HEIGHT;
function flatten(array $array) {
$return = [];
array_walk_recursive($array, static function($a) use (&$return) { $return[] = $a; });
return implode('', $return);
}
$layers = array_map(static function($layer) {
return str_split($layer, WIDTH);
}, str_split($input, $area));
$final_image = array_fill(0, HEIGHT, []);
$final_image = array_map(static function() {
return array_fill(0, WIDTH, TRANSPARENT);
}, $final_image);
foreach ($layers as $layer) {
foreach ($layer as $row => $line) {
$numbers = str_split($line);
foreach ($numbers as $col => $number) {
if ($final_image[$row][$col] == TRANSPARENT) {
$final_image[$row][$col] = $number;
}
}
}
}
$image = new Imagick();
$white = new \ImagickPixel('#FFFFFF');
$black = new \ImagickPixel('#000000');
$image->newImage(WIDTH * 10, HEIGHT * 10, 'none');
$image->setImageFormat('png');
$draw = new \ImagickDraw();
foreach ($final_image as $j => $row) {
foreach ($row as $i => $cell) {
$color = 'none';
if ($cell == WHITE) {
$color = $white;
}
if ($cell == BLACK) {
$color = $black;
}
$draw->setFillColor($color);
$draw->rectangle(10 * $i, 10 * $j, 10 * $i + 10, 10 * $j + 10);
}
}
$image->drawImage($draw);
header("Content-Type: image/png");
$data = $image->getImageBlob();
file_put_contents('part_2.png', $data);