Skip to content

Instantly share code, notes, and snippets.

@MSeven
Created June 1, 2010 21:06
Show Gist options
  • Save MSeven/421492 to your computer and use it in GitHub Desktop.
Save MSeven/421492 to your computer and use it in GitHub Desktop.
Trim a Solid color border from an image using GDlib in PHP
<?php
function imagetrim(&$im) {
$width = imagesx($im);
$height = imagesy($im);
$imcopy = imagecreatetruecolor($width, $height);
imagecopy($imcopy, $im, 0, 0, 0, 0, $width, $height);
imagefilter($imcopy, IMG_FILTER_GAUSSIAN_BLUR);
imagetruecolortopalette($imcopy, false, 32);
$bg = imagecolorat($imcopy, 0, 0);
$xmin = $width;
$ymin = $height;
$xmax = 0;
$ymax = 0;
foreach (range($height - 1, 0) as $y) {
foreach (range($width - 1, 0) as $x) {
if (imagecolorat($imcopy, $x, $y) != $bg) {
if ($x > $xmax) {
$xmax = $x;
}
if ($y > $ymax) {
$ymax = $y;
}
if ($x < $xmin) {
$xmin = $x;
}
if ($y < $ymin) {
$ymin = $y;
}
}
}
}
$newwidth = $xmax - $xmin;
$newheight = $ymax - $ymin;
$im2 = imagecreatetruecolor($newwidth, $newheight);
$bg2 =
imagecolorallocate($im2, 255, 255, 255); // white
imagefill($im2, 0, 0, $bg2);
imagecopy($im2, $im, 0, 0, $xmin, $ymin, $newwidth, $newheight);
$im = $im2;
imagedestroy($imcopy);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment