Created
June 1, 2010 21:06
-
-
Save MSeven/421492 to your computer and use it in GitHub Desktop.
Trim a Solid color border from an image using GDlib in PHP
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 | |
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