Created
November 5, 2012 11:41
-
-
Save davestevens/4016818 to your computer and use it in GitHub Desktop.
Remove whitespace from around image.
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 | |
/* Crop images */ | |
/* Find whitespace around image and remove */ | |
$border = 5; | |
/* Get image */ | |
$orig = getImage($argv[1]); | |
/* */ | |
$imagesize = getimagesize($argv[1]); | |
$width = $imagesize[0]; | |
$height = $imagesize[1]; | |
unset($imagesize); | |
/* Find whitespace around edge of $orig */ | |
$x_min = getXMin($orig, $width, $height); | |
$x_max = getXMax($orig, $width, $height); | |
$y_min = getYmin($orig, $width, $height); | |
$y_max = getYmax($orig, $width, $height); | |
/* Create a new image */ | |
$im = imagecreatetruecolor(($x_max - $x_min) + (2 * $border), ($y_max - $y_min) + (2 * $border)); | |
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF); | |
imagefill($im, 0, 0, $white); | |
/* Copy section of $orig */ | |
imagecopy($im, $orig, 0, 0, ($x_min - $border), ($y_min - $border), (($x_max - $x_min) + $border), (($y_max - $y_min) + $border)); | |
header('Content-Type: image/png'); | |
imagepng($im); | |
imagedestroy($orig); | |
imagedestroy($im); | |
exit(0); | |
function getXMin($im, $w, $h) { | |
for($x=0;$x<$w;++$x) { | |
for($y=0;$y<$h;++$y) { | |
if(imagecolorat($im, $x, $y) != 0xFFFFFF) { | |
return $x; | |
} | |
} | |
} | |
} | |
function getYMin($im, $w, $h) { | |
for($y=0;$y<$h;++$y) { | |
for($x=0;$x<$w;++$x) { | |
if(imagecolorat($im, $x, $y) != 0xFFFFFF) { | |
return $y; | |
} | |
} | |
} | |
} | |
function getXMax($im, $w, $h) { | |
for($x=($w-1);$x>=0;--$x) { | |
for($y=0;$y<$h;++$y) { | |
if(imagecolorat($im, $x, $y) != 0xFFFFFF) { | |
return $x; | |
} | |
} | |
} | |
} | |
function getYMax($im, $w, $h) { | |
for($y=($h-1);$y>=0;--$y) { | |
for($x=0;$x<$w;++$x) { | |
if(imagecolorat($im, $x, $y) != 0xFFFFFF) { | |
return $y; | |
} | |
} | |
} | |
} | |
function getImage($filename) { | |
$type = exif_imagetype($filename); | |
switch($type) { | |
case IMAGETYPE_GIF: | |
return imagecreatefromgif($filename); | |
break; | |
case IMAGETYPE_JPEG: | |
return imagecreatefromjpeg($filename); | |
break; | |
case IMAGETYPE_PNG: | |
return imagecreatefrompng($filename); | |
break; | |
case IMAGETYPE_BMP: | |
return imagecreatefromwbmp($filename); | |
break; | |
default: | |
print 'UNKNOWN IMAGE TYPE: ' . image_type_to_mime_type($type) . "\n"; | |
return FALSE; | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment