Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To trim all whitespace, as you call it, surrounding the interesting part of the image, first we find out where the "whitespace" stops, and then we copy everything inside of those borders.</p> <pre><code>//load the image $img = imagecreatefromjpeg("http://ecx.images-amazon.com/images/I/413XvF0yukL._SL500_AA280_.jpg"); //find the size of the borders $b_top = 0; $b_btm = 0; $b_lft = 0; $b_rt = 0; //top for(; $b_top &lt; imagesy($img); ++$b_top) { for($x = 0; $x &lt; imagesx($img); ++$x) { if(imagecolorat($img, $x, $b_top) != 0xFFFFFF) { break 2; //out of the 'top' loop } } } //bottom for(; $b_btm &lt; imagesy($img); ++$b_btm) { for($x = 0; $x &lt; imagesx($img); ++$x) { if(imagecolorat($img, $x, imagesy($img) - $b_btm-1) != 0xFFFFFF) { break 2; //out of the 'bottom' loop } } } //left for(; $b_lft &lt; imagesx($img); ++$b_lft) { for($y = 0; $y &lt; imagesy($img); ++$y) { if(imagecolorat($img, $b_lft, $y) != 0xFFFFFF) { break 2; //out of the 'left' loop } } } //right for(; $b_rt &lt; imagesx($img); ++$b_rt) { for($y = 0; $y &lt; imagesy($img); ++$y) { if(imagecolorat($img, imagesx($img) - $b_rt-1, $y) != 0xFFFFFF) { break 2; //out of the 'right' loop } } } //copy the contents, excluding the border $newimg = imagecreatetruecolor( imagesx($img)-($b_lft+$b_rt), imagesy($img)-($b_top+$b_btm)); imagecopy($newimg, $img, 0, 0, $b_lft, $b_top, imagesx($newimg), imagesy($newimg)); //finally, output the image header("Content-Type: image/jpeg"); imagejpeg($newimg); </code></pre> <p>My old example, that assumes an identical "border" on all sides of the image, just to clarify the comments :)</p> <pre><code>//load the image $img = imagecreatefromjpeg("img.jpg"); //find the size of the border. $border = 0; while(imagecolorat($img, $border, $border) == 0xFFFFFF) { $border++; } //copy the contents, excluding the border //This code assumes that the border is the same size on all sides of the image. $newimg = imagecreatetruecolor(imagesx($img)-($border*2), imagesy($img)-($border*2)); imagecopy($newimg, $img, 0, 0, $border, $border, imagesx($newimg), imagesy($newimg)); //finally, if you want, overwrite the original image imagejpeg($newimg, "img.jpg"); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload