Skip to content

Instantly share code, notes, and snippets.

@mgdm
Created April 8, 2013 14:05
Show Gist options
  • Save mgdm/5336997 to your computer and use it in GitHub Desktop.
Save mgdm/5336997 to your computer and use it in GitHub Desktop.
'Pixellate' a graphic based on mesh gradients
<?php
define('BOX_WIDTH', 45);
define('BOX_MARGIN', 5);
$image = imagecreatefromjpeg('callanish.jpg');
$width = imagesx($image);
$height = imagesy($image);
$s = new CairoImageSurface(CairoFormat::ARGB32, $width, $height);
$c = new CairoContext($s);
$c->setSourceRGB(0, 0, 0);
$c->rectangle(0, 0, $width, $height);
$c->fill();
function getColourAt($image, $x, $y) {
$colour = imagecolorat($image, $x, $y);
$r = $colour >> 16;
$g = ($colour >> 8) & 255;
$b = $colour & 255;
$r = ($r == 0) ? 0 : 1 / (255 / $r);
$g = ($g == 0) ? 0 : 1 / (255 / $g);
$b = ($b == 0) ? 0 : 1 / (255 / $b);
return array($r, $g, $b);
}
function roundRect(CairoContext $c, $x, $y, $width, $height, $aspect, $radius) {
$radius = $radius / $aspect;
$degrees = M_PI / 180.0;
$c->newSubPath();
$c->arc($x + $width - $radius, $y + $radius, $radius, -90 * $degrees, 0 * $degrees);
$c->arc($x + $width - $radius, $y + $height - $radius, $radius, 0 * $degrees, 90 * $degrees);
$c->arc($x + $radius, $y + $height - $radius, $radius, 90 * $degrees, 180 * $degrees);
$c->arc($x + $radius, $y + $radius, $radius, 180 * $degrees, 270 * $degrees);
$c->closePath();
}
for ($x = 0; $x < ($width - BOX_WIDTH); $x += BOX_WIDTH + BOX_MARGIN) {
for ($y = 0; $y < ($height - BOX_WIDTH); $y += BOX_WIDTH + BOX_MARGIN) {
$colour1 = getColourAt($image, $x, $y);
$colour2 = getColourAt($image, $x + BOX_WIDTH, $y);
$colour3 = getColourAt($image, $x + BOX_WIDTH, $y + BOX_WIDTH);
$colour4 = getColourAt($image, $x, $y + BOX_WIDTH);
$pattern = new CairoMeshPattern();
$pattern->beginPatch();
$pattern->moveTo($x, $y);
$pattern->lineTo($x + BOX_WIDTH, $y);
$pattern->lineTo($x + BOX_WIDTH, $y + BOX_WIDTH);
$pattern->lineTo($x, $y + BOX_WIDTH);
$pattern->setCornerColorRGB(0, $colour1[0], $colour1[1], $colour1[2]);
$pattern->setCornerColorRGB(1, $colour2[0], $colour2[1], $colour2[2]);
$pattern->setCornerColorRGB(2, $colour3[0], $colour3[1], $colour3[2]);
$pattern->setCornerColorRGB(3, $colour4[0], $colour4[1], $colour4[2]);
$pattern->endPatch();
$c->setSource($pattern);
roundRect($c, $x, $y, BOX_WIDTH, BOX_WIDTH, 1.0, BOX_WIDTH / 5);
$c->fill();
}
}
$s->writeToPng('output.png');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment