PHP: 从具有透明背景的 PNG 获取真实图像大小
PHP: Get real image size from PNG with transparent bg
我有透明 BG 的图像,我需要在透明 BG 中获得真实尺寸的图片...
(图像可以是 500x500,但画中画可以是 440x250,我需要得到这个尺寸 - 440x250)...如何在 PHP 和 GD 中做到这一点?
谢谢
因此实际图像大小是 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
我有透明 BG 的图像,我需要在透明 BG 中获得真实尺寸的图片...
(图像可以是 500x500,但画中画可以是 440x250,我需要得到这个尺寸 - 440x250)...如何在 PHP 和 GD 中做到这一点?
谢谢
因此实际图像大小是 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