Skip to content

Instantly share code, notes, and snippets.

@seanlinehan
Created October 4, 2012 03:07
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save seanlinehan/3831235 to your computer and use it in GitHub Desktop.
Save seanlinehan/3831235 to your computer and use it in GitHub Desktop.
Create a pure-CSS version of any image
// Do whatever you'd like with the script! Show it off, mod it up, post it places, or whatever. :)
// (If you do, I wouldn't mind a Twitter shoutout at @_slinehan when appropriate!)
$imageURL = "URL HERE";
$image = imagecreatefromjpeg($imageURL);
$width = imagesx($image);
$height = imagesy($image);
// First, let's resize the image to something manageable while maintaining aspect ratio.
if($height >= $width) {
$nheight = 250;
$nwidth = 250 * ($width/$height);
} else {
$nwidth = 250;
$nheight = 250 * ($height/$width);
}
$thumb = imagecreatetruecolor($nwidth, $nheight);
imagecopyresampled($thumb, $image, 0, 0, 0, 0, $nwidth, $nheight, $width, $height);
// Now we just loop through all of the pixel data
// (We are going to throw out half the data for a bit of a speed boost.
$x = $nwidth-1;
$y = $nheight-1;
for($i = 0; $i < $x; $i++) {
for($j = 0; $j < $y; $j++) {
// Grab the color at the pixel
$at = imagecolorat($thumb, $i, $j);
$hex = getHex((0xFF & ($at >> 0x10)),(0xFF & ($at >> 0x8)),(0xFF & ($at)));
$del = ($i == $x ? ";":",");
// Print out the line of CSS
// We are going to output at 2x size, so 500px
$px = $i*2; $py = $j*2;
echo $px."px ".$py."px 0px 2px ".$hex.",<br/>";
}
}
imagedestroy($thumb);
function getHex($r, $g, $b)
{
$r = dechex($r<0?0:($r>255?255:$r));
$g = dechex($g<0?0:($g>255?255:$g));
$b = dechex($b<0?0:($b>255?255:$b));
$color = (strlen($r) < 2?'0':'').$r;
$color .= (strlen($g) < 2?'0':'').$g;
$color .= (strlen($b) < 2?'0':'').$b;
return '#'.$color;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment