PHP:使用透明背景从PNG获取真实图像大小

PHP:使用透明背景从PNG获取真实图像大小,php,image,png,gd,Php,Image,Png,Gd,我有图像与透明背景和di需要得到真实大小的图片在透明背景 (图像可以是500x500,但图像中的图片可以是440x250,我需要得到这个尺寸-440x250)。。。。如何在PHP和GD中实现这一点 谢谢所以实际图像大小是x侧最后一个不透明像素-x侧第一个不透明像素,y侧相同。所以你所需要的就是找到他们:) 然后,transparent是alpha是127:一个介于0和127之间的值。0表示完全不透明,而127表示完全透明。-这就是您的答案 <?php $image = 'test.png'

我有图像与透明背景和di需要得到真实大小的图片在透明背景

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


谢谢

所以实际图像大小是x侧最后一个不透明像素-x侧第一个不透明像素,y侧相同。所以你所需要的就是找到他们:)

然后,transparent是
alpha
是127:
一个介于0和127之间的值。0表示完全不透明,而127表示完全透明。
-这就是您的答案

<?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