Skip to content

Instantly share code, notes, and snippets.

@jawb
Last active July 31, 2016 14:23
Show Gist options
  • Save jawb/49eec1ec585bdbb9cad6 to your computer and use it in GitHub Desktop.
Save jawb/49eec1ec585bdbb9cad6 to your computer and use it in GitHub Desktop.
Image to CSS
<?php
/*
Demos:
https://jsbin.com/gakudi/1/edit?output
https://jsbin.com/xunifo/edit?output
Usage:
php cssImage.php scale image output
*/
function rgb2hex($rgb) {
return '#' . sprintf('%02x', $rgb['red']) . sprintf('%02x', $rgb['green']) . sprintf('%02x', $rgb['blue']);
}
$scale = (int) $argv[1];
$data = file_get_contents($argv[2]);
$html = "<style>body{margin:0;padding:0;} #canvas{width:{$scale}px;height:{$scale}px;margin:0;";
$im = imagecreatefromstring($data);
$w = imagesx($im);
$h = imagesy($im);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
for ($x = 0; $x < $w; $x++) {
for ($y = 0; $y < $h; $y++) {
$rgb = imagecolorat($im, $x, $y);
$color = imagecolorsforindex($im, $rgb);
$color = rgb2hex($color);
if ($x === 0 && $y === 0) {
$html .= "background:$color; box-shadow:";
} else {
$x1 = $scale * $x;
$y1 = $scale * $y;
$html .= "{$x1}px {$y1}px 0 $color,";
}
}
}
$html = trim($html, ',');
$html .= ";}</style><div id='canvas'></div>";
file_put_contents($argv[3], $html);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment