我如何将 imagecropauto() 与 IMG_CROP_TRANSPARENT 一起使用?

how do i use imagecropauto() with IMG_CROP_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);
    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);

我最终得到一个 red_crop_trans.png 图像,它是一个 300x300px 黑色图像,其中有一个 100x100px 红色圆圈。 还有一个 red_crop_sides.png,它是一个 100x100px 黑色图像,里面有一个 100x100px 红色圆圈。

为什么 red_crop_trans.png 没有裁剪成 100x100px?为什么两个图像的背景都是黑色的?我如何在保持透明度的同时裁剪它们?

我花了一段时间才弄清楚到底发生了什么。原来 $i2 = imagecropauto($i, IMG_CROP_TRANSPARENT); 返回的是 false 而不是 true。根据文档:

imagecropauto() returns FALSE when there is either nothing to crop or the whole image would be cropped.

所以我用 IMG_CROP_DEFAULT:

而不是 IMG_CROP_TRANSPARENT

Attempts to use IMG_CROP_TRANSPARENT and if it fails it falls back to 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);

?>