php 截取图片并设置背景为透明背景图
public function cutImg($target_width,$target_height,$source_x,$source_y,$source_path)
{
$source_info = getimagesize($source_path);
$source_mime = $source_info['mime'];
$cropped_width = $target_width;
$cropped_height = $target_height;
switch ($source_mime)
{
case 'image/gif':
$source_image = imagecreatefromgif($source_path);
break;
case 'image/jpeg':
$source_image = imagecreatefromjpeg($source_path);
break;
case 'image/png':
$source_image = imagecreatefrompng($source_path);
break;
default:
return false;
break;
}
imagesavealpha($source_image, true);
$cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);
$color=imagecolorallocatealpha($cropped_image,0,0,0,127);
imagefill($cropped_image, 0, 0, $color);
imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width,$cropped_height);
$alpha = imagecolorallocatealpha($cropped_image, 0, 0, 0, 127);
imagecolortransparent($cropped_image,$alpha);
imagefill($cropped_image, 0, 0, $alpha);
$res = imagepng($cropped_image,'a.png');
}