工作中需要缩放一些png图然后在去Imagecopymerge,可是发现使用了imagecreatetruecolor和imagecopyresampled后发现本来透明的背景图变成了黑色。
转载代码(自http://www.jb51.net/article/56262.htm):
$img = imagecreatetruecolor(200, 200);
//2.上色
$color=imagecolorallocate($img,255,255,255);
//3.设置透明
imagecolortransparent($img,$color);
imagefill($img,0,0,$color);
然后再进行imagecopyresampled和Imagecopymerge就没有问题了
个人项目代码:
class uploadImg {
var $smallFolder = "../upload/";//缩略图存放路径
function getInfo($photo) {
$imageInfo = getimagesize($photo);
$imgInfo["width"] = $imageInfo[0];
$imgInfo["height"] = $imageInfo[1];
$imgInfo["type"] = $imageInfo[2];
$imgInfo["name"] = basename($photo);
$name = explode(".",$photo);//将上传前的文件以“.”分开取得文件类型
$imgCount = count($name);//获得截取的数量
$imgInfo["extension"] = $name[$imgCount-1];//取得文件的类型
return $imgInfo;
}
function smallImg($photo,$smallFolder,$width=128,$height=128,$limit=false) {
if($smallFolder!='') $this->smallFolder = $smallFolder;
$imgInfo = $this->getInfo($photo);
$newName = substr($imgInfo["name"],0,strrpos($imgInfo["name"], ".")).".".$imgInfo["extension"];//新图片名称
if($imgInfo["type"] == 1) {
$img = imagecreatefromgif($photo);
} elseif($imgInfo["type"] == 2) {
$img = imagecreatefromjpeg($photo);
} elseif($imgInfo["type"] == 3) {
$img = imagecreatefrompng($photo);
} else {
$img = "";
}
if(empty($img)) return False;
if($limit==true){
$width = ($width > $imgInfo["width"]) ? $imgInfo["width"] : $width;
$height = ($height > $imgInfo["height"]) ? $imgInfo["height"] : $height;
$srcW = $imgInfo["width"];
$srcH = $imgInfo["height"];
if ($srcW * $width > $srcH * $height) {
$height = round($srcH * $width / $srcW);
} else {
$width = round($srcW * $height / $srcH);
}
}
if (function_exists("imagecreatetruecolor")) {
$newImg = imagecreatetruecolor($width, $height);
/* --- 用以处理缩放png图透明背景变黑色问题 开始 --- */
if(strtolower($imgInfo["extension"])=='png' || strtolower($imgInfo["extension"])=='gif'){
$color = imagecolorallocate($newImg,255,255,255);
imagecolortransparent($newImg,$color);
imagefill($newImg,0,0,$color);
}
/* --- 用以处理缩放png图透明背景变黑色问题 结束 --- */
ImageCopyResampled($newImg, $img, 0, 0, 0, 0, $width, $height, $imgInfo["width"], $imgInfo["height"]);
} else {
$newImg = imagecreate($width, $height);
ImageCopyResized($newImg, $img, 0, 0, 0, 0, $width, $height, $imgInfo["width"], $imgInfo["height"]);
}
if ($this->toFile) {
if (file_exists($this->smallFolder.$newName)) @unlink($this->smallFolder.$newName);
ImageJPEG($newImg,$this->smallFolder.$newName,100);
return $newName;
} else {
ImageJPEG($newImg);
}
ImageDestroy($newImg);
ImageDestroy($img);
return $newName;
}
}