由于 GD 函数,我目前正在尝试使用图片和 PHP。现在我想修改PNG图片的大小。这是我想调整大小的 PNG 示例:

虚线代表PNG的边框,背景是透明的,我只在大空间中间丢了一颗星星。我想裁剪这颗星星,得到一个简单的星星方块(即使新背景变成空白,也没关系)。
我怎么能有效地做这样的事情?我想做一个循环检查图片的每个像素..试图找到图像的位置,最后根据最小 x / 最大 X 和最小 y / 最大 y 值裁剪一点边距,但如果我开始工作有数百张照片,这会很长。
编辑 :
<?php
$file = "./crop.png";
$ext = pathinfo($file, PATHINFO_EXTENSION);
$image;
switch ($ext){
case 'png':
$image = imagecreatefrompng($file);
break;
case 'jpeg':
case 'jpg':
$image = imagecreatefromjpeg($file);
break;
case 'gif':
$image = imagecreatefromgif($file);
break;
}
$cropped = imagecropauto($image, IMG_CROP_DEFAULT);
if ($cropped !== false) { // in case a new image resource was returned
echo "=> Cropping needed\n";
imagedestroy($image); // we destroy the original image
$image = $cropped; // and assign the cropped image to $im
}
imagepng($image, "./cropped.png");
imagedestroy($image);
Run Code Online (Sandbox Code Playgroud)
如果您阅读并遵循php php-gd文档,您会发现一个名为的函数imagecropauto,它完全符合您的要求,它裁剪图像的 alpha 通道。
使用 alpha 通道裁剪 PNG 图像
$im = imagecreatefrompng("./star-with-alpha.png");
$cropped = imagecropauto($im, IMG_CROP_DEFAULT);
if ($cropped !== false) { // in case a new image resource was returned
imagedestroy($im); // we destroy the original image
$im = $cropped; // and assign the cropped image to $im
}
imagepng($im, "./star-with-alpha-crop.png");
imagedestroy($im);
Run Code Online (Sandbox Code Playgroud)
您可以使用以下代码直接尝试到 php 页面:
<body>
<img src="star-with-alpha.png">
<?php
$im = imagecreatefrompng("./star-with-alpha.png");
$cropped = imagecropauto($im, IMG_CROP_DEFAULT);
if ($cropped !== false) { // in case a new image resource was returned
imagedestroy($im); // we destroy the original image
$im = $cropped; // and assign the cropped image to $im
}
imagepng($im, "./star-with-alpha-crop.png");
imagedestroy($im);
?>
<img src="star-with-alpha-crop.png">
</body>
Run Code Online (Sandbox Code Playgroud)
结果
http://zikro.gr/dbg/php/crop-png/