是否可以在PHP中删除图像周围的空格?
注意:澄清一下,我的意思是像photoshops装饰功能。
谢谢。
要修剪所有空白,就像您所说的那样,围绕图像的有趣部分,首先我们找出“空白”在哪里停止,然后我们复制这些边界内的所有内容。
//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 < imagesy($img); ++$b_top) { for($x = 0; $x < imagesx($img); ++$x) { if(imagecolorat($img, $x, $b_top) != 0xFFFFFF) { break 2; //out of the 'top' loop } } } //bottom for(; $b_btm < imagesy($img); ++$b_btm) { for($x = 0; $x < imagesx($img); ++$x) { if(imagecolorat($img, $x, imagesy($img) - $b_btm-1) != 0xFFFFFF) { break 2; //out of the 'bottom' loop } } } //left for(; $b_lft < imagesx($img); ++$b_lft) { for($y = 0; $y < imagesy($img); ++$y) { if(imagecolorat($img, $b_lft, $y) != 0xFFFFFF) { break 2; //out of the 'left' loop } } } //right for(; $b_rt < imagesx($img); ++$b_rt) { for($y = 0; $y < 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);
我的旧示例假设图像的所有侧面都具有相同的“边框”,只是为了澄清注释:)
//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");