使用GD库的imagerotate方法或者imagick的rotateimage方法对图片旋转后,图片未覆盖区域背景颜色默认为黑色(图1),设置为透明色的解决方法如下:
GD:
resource imagerotate ( resource $image , float $angle , int $bgd_color [, int $ignore_transparent = 0 ] )
使用imagecolorallocatealpha方法生成bgd_color,最后传入alpha透明值
代码示例:
$logo_file = './Public/assets/images/gallery/logo.png'; $logo_info = getimagesize($logo_file); $logo_type = image_type_to_extension($logo_info[2], false); $logo_fun = "imagecreatefrom{$logo_type}"; $logo = $logo_fun($logo_file); imagesavealpha($logo, true); //设置bgcolor $pngTransparency = imagecolorallocatealpha($logo, 0, 0, 0, 127); imagefill($logo, 0, 0, $pngTransparency); $rotate = imagerotate($logo, 120, $pngTransparency);
ImageMagick:
bool Imagick::rotateImage ( mixed $background , float $degrees )
$background使用rgba格式
$logo->rotateImage(new \ImagickPixel("rgba(250,15,150,0)"), 60);
实现效果见图2
图1
图2