在png图像中找到旋转透明矩形的4个坐标

时间:2016-05-05 04:37:57

标签: php png gd alpha

我没有找到关于这个主题的任何内容,但我是在生动地做梦,还是可以在PHP中扫描PNG图像并找到图片中的透明位置?

例如,如果有一个带有透明孔的电视的图像,屏幕就是。我可以通过扫描Alpha通道找到透明像素的最左上角,最右上角,最左下角,最右下角的坐标吗?

不确定是否有图书馆这样做,我检查得很快但没找到..

1 个答案:

答案 0 :(得分:0)

也许不是最优雅的解决方案,我确信有更好的方法,但这适用于格式良好的png图像

// Returns the coordinates of a transparent rectangle in a PNG file (top left, top right, lower left, lower right
public function getTransparentRectangleCoordinates($fileUrl)
{
    define ('TRANSPARENCY_THRESHOLD', 100); // 127=fully transparent, 0=black

    $img = @imagecreatefrompng($fileUrl);

    if (!$img) return ('Invalid PNG Image');

    $coordLowestX = array(imagesx($img), '');
    $coordHighestX = array(0, '');
    $coordLowestY = array('', imagesy($img));
    $coordHighestY = array('', 0);

    $minX = imagesx($img);
    $maxX = 0;
    $minY = imagesy($img);
    $maxY = 0;

    // Scanning image pixels to find transparent points
    for ($x=0; $x < imagesx($img); ++$x)
    {
        for ($y=0; $y < imagesy($img); ++$y)
        {
            $alpha = (imagecolorat($img, $x, $y) >> 24) & 0xFF;
            if ($alpha >= TRANSPARENCY_THRESHOLD)
            {
                if ($x < $coordLowestX[0]) $coordLowestX = array($x, $y);
                if ($x > $coordHighestX[0]) $coordHighestX = array($x, $y);
                if ($y < $coordLowestY[1]) $coordLowestY = array($x, $y);
                if ($y >= $coordHighestY[1]) $coordHighestY = array($x, $y);

                if ($x < $minX) $minX = $x;
                if ($x > $maxX) $maxX = $x;

                if ($y < $minY) $minY = $y;
                if ($y > $maxY) $maxY = $y;
            }
        }
    }

    // This means it's a non-rotated rectangle
    if ( $coordLowestX == array($minX, $minY) )
    {
        $isRotated = false;

        return array( array($minX, $minY), array($maxX, $minY), array($minX, $maxY), array($maxX, $maxY) );
    }
    // This means it's a rotated rectangle
    else
    {
        $isRotated = true;

        // Rotated counter-clockwise
        if ($coordLowestX[1] < $coordHighestX[1])
            return array($coordLowestX, $coordLowestY, $coordHighestY, $coordHighestX);
        else // Rotated clockwise
            return array($coordLowestY, $coordHighestY, $coordLowestX, $coordHighestX);
    }
}