使用GD库从现有图像中删除黑色边缘

时间:2012-10-12 01:02:55

标签: php image gd

我正在下载已经有黑边的图像。注意:这不是我调整图像大小的结果。如何使用GD库检测并删除这些黑边?

enter image description here

enter image description here

更新

这是使用脚本的裁剪图像 enter image description here

1 个答案:

答案 0 :(得分:4)

我能够想出一个耗时的解决方案。存储的图像是否需要与黑色边框一起存储?如果您可以通过以下脚本运行带有黑色边框的每个图像(使用php循环遍历目录中的每个图像)并让php使用新的无边框图像覆盖旧的黑色边框图像,那会好得多。

我采取的方法是创建4个循环:

  1. 要查看右侧的黑色边框(循环显示x - >循环显示y)
  2. 查看左侧的黑色边框(循环显示x - >循环显示y)
  3. 查看底部的黑色边框(循环显示y - >循环显示x)
  4. 查看顶部的黑色边框(循环显示y - >循环显示x)
  5. 现在,这些循环中的每一个在其中具有另一个循环,其将循环通过另一个坐标(即,x-> y或y-> x)。如果内环发现位于外环线上的一个像素不是黑色,则会破坏整个外观。如果没有找到,那就会增加一个到柜台。

    最后,我们只需使用新尺寸创建一个新图像,然后从新图像复制到旧图像。

    <?php
    $image_path = "jcMHt.jpg";
    
    $jpg = imagecreatefromjpeg($image_path);
    $black = array("red" => 0, "green" => 0, "blue" => 0, "alpha" => 0);
    
    $removeLeft = 0;
    for($x = 0; $x < imagesx($jpg); $x++) {
        for($y = 0; $y < imagesy($jpg); $y++) {
            if(imagecolorsforindex($jpg, imagecolorat($jpg, $x, $y)) != $black){
                break 2;
            }
        }
        $removeLeft += 1;
    }
    
    $removeRight = 0;
    for($x = imagesx($jpg)-1; $x > 0; $x--) {
        for($y = 0; $y < imagesy($jpg); $y++) {
            if(imagecolorsforindex($jpg, imagecolorat($jpg, $x, $y)) != $black){
                break 2;
            }
        }
        $removeRight += 1;
    }
    
    $removeTop = 0;
    for($y = 0; $y < imagesy($jpg); $y++) {
        for($x = 0; $x < imagesx($jpg); $x++) {
            if(imagecolorsforindex($jpg, imagecolorat($jpg, $x, $y)) != $black){
                break 2;
            }
        }
        $removeTop += 1;
    }
    
    $removeBottom = 0;
    for($y = imagesy($jpg)-1; $y > 0; $y--) {
        for($x = 0; $x < imagesx($jpg); $x++) {
            if(imagecolorsforindex($jpg, imagecolorat($jpg, $x, $y)) != $black){
                break 2;
            }
        }
        $removeBottom += 1;
    }
    
    $cropped = imagecreatetruecolor(imagesx($jpg) - ($removeLeft + $removeRight), imagesy($jpg) - ($removeTop + $removeBottom));
    imagecopy($cropped, $jpg, 0, 0, $removeLeft, $removeTop, imagesx($cropped), imagesy($cropped));
    
    header("Content-type: image/jpeg");
    imagejpeg($cropped); //change to `imagejpeg($cropped, $image_path);` to save
    imagedestroy($cropped);
    imagedestroy($jpg);