Last active
July 31, 2016 14:23
Image to CSS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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