当我尝试裁剪图像的透明区域时,它会保持原始大小,并且透明区域变黑.
如果我运行此代码:
<?php
// Create a 300x300px transparant image with a 100px wide red circle in the middle
$i = imagecreatetruecolor(300, 300);
imagealphablending($i, FALSE);
imagesavealpha($i, TRUE);
$transparant = imagecolorallocatealpha($i, 0xDD, 0xDD, 0xDD, 0x7F);
imagefill($i, 0, 0, $transparant);
$red = imagecolorallocate($i, 0xFF, 0x0, 0x0);
imagefilledellipse($i, 150, 150, 100, 100, $red);
imagepng($i, "red_300.png");
// Crop away transparant parts and save
$i2 = imagecropauto($i, IMG_CROP_TRANSPARENT);
imagepng($i2, "red_crop_trans.png");
imagedestroy($i2);
// Crop away bg-color parts and save
$i2 = imagecropauto($i, IMG_CROP_SIDES);
imagepng($i2, "red_crop_sides.png");
imagedestroy($i2);
// clean up org image
imagedestroy($i);
Run Code Online (Sandbox Code Playgroud)
我最终得到的red_crop_trans.png图像是一个300x300px黑色图像,里面有一个100x100px红色圆圈.还有一个red_crop_sides.png是100x100px黑色图像,里面有一个100x100px红色圆圈.
为什么red_crop_trans.png没有被破坏100x100px?为什么两个图像的背景都是黑色的?如何在保持transparace的同时裁剪它们?
我花了一段时间才弄清楚到底发生了什么。事实证明$i2 = imagecropauto($i, IMG_CROP_TRANSPARENT);返回的是 false 而不是 true。根据文档:
当没有任何内容可裁剪或整个图像将被裁剪时,imagecropauto() 返回 FALSE。
所以IMG_CROP_TRANSPARENT我用的是IMG_CROP_DEFAULT:
尝试使用 IMG_CROP_TRANSPARENT,如果失败,则返回到 IMG_CROP_SIDES。
这给了我预期的结果。现在我自己没有得到任何黑色背景。但这是一个已知问题,因此很容易找到解决方案:
imagecolortransparent($i, $transparant); // Set background transparent
这让我看到了最终完成的代码:
<?php
// Create a 300x300px transparant image with a 100px wide red circle in the middle
$i = imagecreatetruecolor(300, 300);
imagealphablending($i, FALSE);
imagesavealpha($i, TRUE);
$transparant = imagecolorallocatealpha($i, 0xDD, 0xDD, 0xDD, 0x7F);
imagecolortransparent($i, $transparant); // Set background transparent
imagefill($i, 0, 0, $transparant);
$red = imagecolorallocate($i, 0xFF, 0x0, 0x0);
imagefilledellipse($i, 150, 150, 100, 100, $red);
imagepng($i, "red_300.png");
// Crop away transparant parts and save
$i2 = imagecropauto($i, IMG_CROP_DEFAULT); //Attempts to use IMG_CROP_TRANSPARENT and if it fails it falls back to IMG_CROP_SIDES.
imagepng($i2, "red_crop_trans.png");
imagedestroy($i2);
// Crop away bg-color parts and save
$i2 = imagecropauto($i, IMG_CROP_SIDES);
imagepng($i2, "red_crop_sides.png");
imagedestroy($i2);
// clean up org image
imagedestroy($i);
?>
Run Code Online (Sandbox Code Playgroud)