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

Find the 4 coordinates of a rotated transparent rectangle in png image

我没有找到关于这个主题的任何信息,但我正在做梦,或者在 PHP 中是否可以扫描 PNG 图像并找到图片中的透明位置?

例如,如果在屏幕所在的位置有一个带有透明孔的电视图像。能否通过扫描alpha通道找到透明像素的最左上角、最右上角、最左下角、最右下角坐标?

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

也许不是最优雅的解决方案,我相信有更好的方法,但这适用于格式正确的 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);
    }
}