This PHP function trims off a color in the outside of the image, and leave a smaller image.
Example:
From this:

To this:

By using this:
$file = "circle.png"; $img = imagecreatefrompng($file); imagepng(imagetrim($img,imagecolorat($img,0,0)),$file);
Source of the function
//Input a image resource and a integer represent color function imagetrim($img,$color){ $mx=imagesx($img); $my=imagesy($img); for($x=0;$x<$mx;++$x){ for($y=0;$y<$my;++$y){ if(imagecolorat($img,$x,$y)!=$color){ $minx = $x; break 2; } } } //The image is filled with $color if($minx==0){ return null; } for($x=$mx-1;$x>$minx;--$x){ for($y=0;$y<$my;++$y){ if(imagecolorat($img,$x,$y)!=$color){ $maxx = $x+1; break 2; } } } for($y=0;$y<$my;++$y){ for($x=$minx;$x<$maxx;++$x){ if(imagecolorat($img,$x,$y)!=$color){ $miny = $y; break 2; } } } for($y=$my-1;$y>$miny;--$y){ for($x=$minx;$x<$maxx;++$x){ if(imagecolorat($img,$x,$y)!=$color){ $maxy = $y+1; break 2; } } } $img2=imagecreatetruecolor($maxx-$minx,$maxy-$miny); imagecopy($img2,$img,0,0,$minx,$miny,$maxx-$minx,$maxy-$miny); return $img2; }
Comments
Post new comment