$tmpfile = $_FILES['Filedata']['tmp_name']; $arr = getimagesize($tmpfile);
switch ($arr["mime"]) {
case "image/jpeg":
$type = "jpeg"; //jpeg file
$imgsrc = imagecreatefromjpeg($tmpfile);
break;
case "image/gif":
$type = "gif"; //gif file
$imgsrc = imagecreatefromgif($tmpfile);
break;
case "image/png":
$type = "png"; //png file
$imgsrc = imagecreatefrompng($tmpfile);
break;
default:
$type = false;
break;
}
$img = imagecreatetruecolor($arr[0], $arr[1]);
imagecopyresampled($img, $imgsrc, 0, 0, 0, 0, $arr[0], $arr[1], $arr[0], $arr[1]);
//水印图像
$imgco=$this->vdata['cdnUrl'].'img/ADSS_logo.png';
$imgco_src= imagecreatefrompng($imgco);
$imgco_info= getimagesize($imgco);
//水印透明度
$alpha = 100;
//合并水印图片
imagecopymerge($img,$imgco_src,($arr[0]-$imgco_info[0])/2,($arr[1]-$imgco_info[1])/2,0,0,$imgco_info[0],$imgco_info[1],$alpha);
$func = 'image' . $type;
if($type=='png')
$result = $func($img, $filePath, 9);
else
$result = $func($img, $filePath, 100);
imagedestroy($img);
实际生产的时候,原png图片为透明的,合并后,为黑色的背景,所以把
//合并水印图片
imagecopymerge($img,$imgco_src,($arr[0]-$imgco_info[0])/2,($arr[1]-$imgco_info[1])/2,0,0,$imgco_info[0],$imgco_info[1],$alpha);
改为
imagecopymerge_alpha($img,$imgco_src,($arr[0]-$imgco_info[0])/2,($arr[1]-$imgco_info[1])/2,0,0,$imgco_info[0],$imgco_info[1],$alpha);
就可以解决该问题
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){ $opacity=$pct; // getting the watermark width $w = imagesx($src_im); // getting the watermark height $h = imagesy($src_im); // creating a cut resource $cut = imagecreatetruecolor($src_w, $src_h); // copying that section of the background to the cut imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h); // inverting the opacity //$opacity = 100 - $opacity; // placing the watermark now imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h); imagecopymerge($dst_im, $cut, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $opacity); }