imagetrim() function

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

Example:
From this:
Circle
To this:
Trimmed circle
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

  • Allowed HTML tags: <img> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <span> <fn>
  • Lines and paragraphs break automatically.
  • Use [fn]...[/fn] (or <fn>...</fn>) to insert automatically numbered footnotes.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. The supported tag styles are: <foo>, [foo].
  • Mathematical equations and graphs can be added between [tex] and [/tex], [graph] and [/graph] tags.
  • Textual smileys will be replaced with graphical ones.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
  _      __         _____                
| |_ / _| ____ |__ / __ __ _ _
| __| | |_ |_ / / / \ \ / / | | | |
| |_ | _| / / / /_ \ V / | |_| |
\__| |_| /___| /____| \_/ \__,_|
Enter the code depicted in ASCII art style.
Honey Pot that kill bots