【发布时间】:2019-04-25 07:35:42
【问题描述】:
我有透明背景的图像,我需要在透明背景中获得真实尺寸的图片...
(图像可以是 500x500,但图像中的图片可以是 440x250,我需要这个尺寸 - 440x250).... 在 PHP 和 GD 中如何做到这一点?
谢谢
【问题讨论】:
我有透明背景的图像,我需要在透明背景中获得真实尺寸的图片...
(图像可以是 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
【讨论】: