note 49210 added to ref.image
| From: | carl at pappenheim dot net | Date: | Thu, 20 Jan 2005 10:43:09 +0000 |
| Subject: | note 49210 added to ref.image | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-83666@lists.php.net to get a copy of this message | ||
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);
}
----
Manual Page -- http://www.php.net/manual/en/ref.image.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+49210
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+49210&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+49210&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+49210&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+49210&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+49210&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+49210&report=yes
Search -- http://master.php.net/manage/user-notes.php