Pixelate Images using PHP
Friday, January 27, 2012 EST
by: Eric Potvin
Tags:php
On January 24th, 2011 "lasers" from StackOverFlow asked how can he make the edges smoother on an image.
Effectivly, the script he uses to generate the pixelate image has very sharp edges. After some digging, I found a very good script.
This script generates a pixelate image with smooth edges and sharp edges.
The smooth edges look way better for my taste and here's what kept from the script:
function convertToPixel($image, $size) {
$im = imagecreatefromjpeg($image);
$size = (int)$size;
$sizeX = imagesx($im);
$sizeY = imagesy($im);
if($sizeX < 3 && $sizeX < 3) { // or you can choose any size you want
return;
}
for($i = 0;$i < $sizeX; $i += $size) {
for($j = 0;$j < $sizeY; $j += $size) {
$colors = Array('alpha' => 0, 'red' => 0, 'green' => 0, 'blue' => 0, 'total' => 0);
for($k = 0; $k < $size; ++$k) {
for($l = 0; $l < $size; ++$l) {
if($i + $k >= $sizeX || $j + $l >= $sizeY) {
continue;
}
$color = imagecolorat($im, $i + $k, $j + $l);
imagecolordeallocate($im, $color);
$colors['alpha'] += ($color >> 24) & 0xFF;
$colors['red'] += ($color >> 16) & 0xFF;
$colors['green'] += ($color >> 8) & 0xFF;
$colors['blue'] += $color & 0xFF;
++$colors['total'];
}
}
$color = imagecolorallocatealpha($im, $colors['red'] / $colors['total'], $colors['green'] / $colors['total'], $colors['blue'] / $colors['total'], $colors['alpha'] / $colors['total']);
imagefilledrectangle($im, $i, $j, ($i + $size - 1), ($j + $size - 1), $color);
}
}
header('Content-type: image/jpg');
imagejpeg($im, '', 100);
}
$image = 'lion.jpg';
convertToPixel($image, 10);
This will convert this image:
To:
If you want to change the pixel size you can simply change the second parameters to a lower or higher number.
Link to this Article
To link directly to this article from your web site, use one of the following snippets below.
Pixelate Images using PHP | Book Of Zeus<a href="http://www.bookofzeus.com/articles/pixelate-images-using-php/" title="Pixelate Images using PHP">Pixelate Images using PHP | Book Of Zeus</a>
Short URL:
Pixelate Images using PHP | Book Of Zeus<a href="http://s.bookofzeus.com/bJDbN" title="Pixelate Images using PHP Short URL">Pixelate Images using PHP | Book Of Zeus</a>