【问题标题】:Find the 4 coordinates of a rotated transparent rectangle in png image在 png 图像中查找旋转透明矩形的 4 个坐标
【发布时间】:2016-08-30 18:16:50
【问题描述】:

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

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

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

【问题讨论】:

    标签: php png gd alpha


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-12-15
      • 2018-11-06
      • 1970-01-01
      • 2011-08-21
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      相关资源
      最近更新 更多