【问题标题】:PHP: Get real image size from PNG with transparent bgPHP:使用透明bg从PNG获取真实图像大小
【发布时间】:2019-04-25 07:35:42
【问题描述】:

我有透明背景的图像,我需要在透明背景中获得真实尺寸的图片...

(图像可以是 500x500,但图像中的图片可以是 440x250,我需要这个尺寸 - 440x250).... 在 PHP 和 GD 中如何做到这一点?

谢谢

【问题讨论】:

    标签: php image png gd


    【解决方案1】:

    所以真正的图像大小是 x 侧的最后一个非透明像素 - x 侧的第一个非透明像素和 y 侧的相同。所以你只需要找到它们:)

    透明的是 alpha 是 127:A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent. - http://php.net/manual/de/function.imagecolorallocatealpha.php - 所以你在这里

    <?php
    $image = 'test.png';
    $image = imagecreatefrompng($image);
    
    $width = imagesx($image);
    $height = imagesy($image);
    
    $colors = array();
    
    $x_max = $y_max = 0;
    $x_min = $width;
    $y_min = $height;
    for ($y = 0; $y < $height; ++$y)
    {
        for ($x = 0; $x < $width; ++$x)
        {
            $rgb = imagecolorat($image, $x, $y);
            $color = imagecolorsforindex($image, $rgb);
    
            if (127 !== $color['alpha']) {
                $x_min = min($x_min, $x);
                $x_max = max($x_max, $x);
                $y_min = min($y_min, $y);
                $y_max = max($y_max, $y);
            }
        } 
    }
    
    echo 'width: ' . ($x_max - $x_min) . PHP_EOL;
    echo 'height: ' . ($y_max - $y_min) . PHP_EOL;
    

    输出:

    width: 180
    height: 180
    

    【讨论】:

      猜你喜欢
      • 2014-04-14
      • 1970-01-01
      • 2018-10-09
      • 2011-05-02
      • 2010-09-23
      • 2013-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多