This is a little runaway.
PHP
1<?php
2
3function isBlack($im, $x, $y)
4{
5 $rgb = imagecolorat($im, $x, $y);
6
7 $r = ($rgb >> 16) & 0xFF;
8 $g = ($rgb >> 8) & 0xFF;
9 $b = $rgb & 0xFF;
10
11 //echo "rgb = {$r}, {$g}, {$b}<br>\n";
12
13 $t = 5; // threshold
14
15 return ($r < $t && $g < $t && $b < $t)? 1 : 0;
16}
17
18function getCropFrom($resource, $max)
19{
20 for($i = 0; $i < $max; $i++)
21 {
22 if($resource[$i] != 0) { return $i; }
23 }
24
25 return 0;
26}
27
28function getCropTo($resource, $max)
29{
30 for($i = $max - 1; $i >= 0; $i--)
31 {
32 if($resource[$i] != 0) { return $i; }
33 }
34
35 return $max - 1;
36}
37
38$im = imagecreatefrompng("php.png");
39
40$rows = array();
41$cols = array();
42
43$width = imagesx($im);
44$height = imagesy($im);
45
46for($y = 0; $y < $height; $y++)
47{
48 for($x = 0; $x < $width; $x++)
49 {
50 $black = isBlack($im, $x, $y)? 1 : 0;
51
52 //echo "{$x}, {$y} = {$black}<br>\n";
53
54 $cols[$x] |= $black;
55 $rows[$y] |= $black;
56 }
57}
58
59//echo implode(" ", $cols) . "<br>\n";
60//echo implode(" ", $rows) . "<br>\n";
61
62$cropX1 = getCropFrom($cols, $width);
63$cropX2 = getCropTo($cols, $width);
64$cropY1 = getCropFrom($rows, $height);
65$cropY2 = getCropTo($rows, $height);
66
67echo "crop ({$cropX1} , {$cropY1}) to ({$cropX2} , {$cropY2})<br>\n";
68
69$im2 = imagecrop($im, ['x' => $cropX1, 'y' => $cropY1, 'width' => ($cropX2 - $cropX1), 'height' => ($cropY2 - $cropY1)]);
70
71if($im2 === false) { echo "crop error."; imagedestroy($im); exit; }
72
73imagepng($im2, './output/example-cropped.png');
74
75echo "crop image was created.";
76
77imagedestroy($im);
78imagedestroy($im2);