note 49210 deleted from ref.image by tularis

From: Date: Sun, 29 Jun 2008 21:10:02 +0000
Subject: note 49210 deleted from ref.image by tularis
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-140961@lists.php.net to get a copy of this message
Note Submitter: carl at pappenheim dot net ---- I notice that there is no pre-made function that is similar to Photoshop's 'trim' function. I appreciate this is very long-winded (a neater version would probably approach the centre in a sort of spiral movement) but at least it works and, hopefully, is clear. The tolerance is effectively zero, and it takes the top left pixel (0,0) as being the background colour that is to be trimmed. $filename = "image_with_white_border.jpg"; $image = imagecreatefromjpeg($filename); if ($image) { $dim = getimagesize($filename); $backgnd = ImageColorAt($image,0,0); for ($x=0;$x<$dim[0];$x++) { for ($y=0;$y<$dim[1];$y++) { if (ImageColorAt($image,$x,$y) != $backgnd) { $trimx = $x; // found left edge break(2); } } } for ($x=$dim[0];$x>=0;$x--) { for ($y=0;$y<$dim[1];$y++) { if (ImageColorAt($image,$x,$y) != $backgnd) { $trimx2 = $x; // found right edge break(2); } } } for ($y=0;$y<$dim[1];$y++) { for ($x=0;$x<$dim[0];$x++) { if (ImageColorAt($image,$x,$y) != $backgnd){ $trimy = $y; // found top edge break(2); } } } for ($y=$dim[1];$y>=0;$y--) { for ($x=0;$x<$dim[0];$x++) { if (ImageColorAt($image,$x,$y) != $backgnd) { $trimy2 = $y; // found bottom edge break(2); } } } $trimxsize = $trimx2-$trimx; // calculate x dimension $trimysize = $trimy2-$trimy; // calculate y dimension $outimage = imagecreatetruecolor($trimxsize, $trimysize); imagecopy($outimage, $image, 0,0, $trimx,$trimy, $trimxsize,$trimysize); header('Content-type: image/jpeg'); imagejpeg($outimage, null, 100); }

« previous php.notes (#140961) next »