Ed9c50a6db8b5e078b5ef84306a8477c

Originally from http://zavaboy.com/2007/10/06/trim_an_image_using_php_and_gd

Could do with a way to detect the background colour automatically (from the bottom-left corner pixel of the image?).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php

function imagetrim(&$im){
  $bg = imagecolorallocate($im, 255, 255, 255); // white
    
  $width = imagesx($im);
  $height = imagesy($im);

  foreach (range($height - 1, 0) as $y)
    foreach (range($width - 1, 0) as $x)
      if (imagecolorat($im, $x, $y) != $bg)
        break 2;

  $im2 = imagecreatetruecolor($width, $y);
  $bg2 = imagecolorallocate($im2, 255, 255, 255); // white
  imagefill($im2, 0, 0, $bg2);
  imagecopy($im2, $im, 0, 0, 0, 0, $width, $y);

  $im = $im2;
}

Refactorings

No refactoring yet !

Avatar

MSeven

April 6, 2008, April 06, 2008 19:20, permalink

No rating. Login to rate!

This is the result of some not very target oriented fiddling and playing.
* Trims borders of the image in both directions.
* Determines color to be cut by looking at the top left pixel.
* Tries to smooth/soften the image for content analysis by applying gauissian blur and reducing it to 32 colors (returned output is still truecolor)

Changing the amount of colors in the palette image used to evaluate image contents allows to fine-tune results.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php

function imagetrim(&$im) {
	
	$width = imagesx($im);
	$height = imagesy($im);
	
	$imcopy = imagecreatetruecolor($width, $height);
	imagecopy($imcopy, $im, 0, 0, 0, 0, $width, $height);
	imagefilter($imcopy, IMG_FILTER_GAUSSIAN_BLUR);
	imagetruecolortopalette($imcopy, false, 32);
	
	$bg = imagecolorat($imcopy, 0, 0);
	
	$xmin = $width;
	$ymin = $height;
	
	$xmax = 0;
	$ymax = 0;
	
	foreach (range($height - 1, 0) as $y) {
		foreach (range($width - 1, 0) as $x) {
			if (imagecolorat($imcopy, $x, $y) != $bg) {
				if ($x > $xmax) {
					$xmax = $x;
				}
				if ($y > $ymax) {
					$ymax = $y;
				}
				if ($x < $xmin) {
					$xmin = $x;
				}
				if ($y < $ymin) {
					$ymin = $y;
				}
			}
		}
	}
	
	$newwidth = $xmax - $xmin;
	$newheight = $ymax - $ymin;
	
	$im2 = imagecreatetruecolor($newwidth, $newheight);
	$bg2 = 
	imagecolorallocate($im2, 255, 255, 255); // white
	imagefill($im2, 0, 0, $bg2);
	imagecopy($im2, $im, 0, 0, $xmin, $ymin, $newwidth, $newheight);
	
	$im = $im2;
	imagedestroy($imcopy);
}

Your refactoring





Format Copy from initial code

or Cancel