``以下代码经试验有效:
/**
* 缩减图片尺寸
* @param $source 图片来源 本地路径
* @return string
*/
public function zoomImg($source)
{
// header("Content-type: image/jpeg");
//获取图片路径
$source_arr = explode("/", $source);
$len = count($source_arr);
if($len > 0)
{
$source_arr[$len - 1] = $source_arr[$len - 1];
$source_new = implode("/", $source_arr);
}
$filename = $source;
$percent = 0.5; //图片压缩比
list($width, $height) = getimagesize($filename); //获取原图尺寸
//缩放尺寸
$newwidth = $width * $percent;
$newheight = $height * $percent;
$new = imagecreatetruecolor($newwidth, $newheight);
$img = imagecreatefromjpeg($filename);
//copy部分图像并调整
imagecopyresampled($new, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//图像输出新图片、另存为
imagejpeg($new,$source_new); //输出压缩后的图片
imagedestroy($new);
imagedestroy($img);
return $source_new;
}
/**
* 合并图片 将png图片转换为jpg格式图片
* @param $source 图片来源 本地路径
* @return string
*/
public function mergePic($srcPath){
$dst_path = $srcPath;
$srcPath = str_replace('.png', '.jpg', $srcPath);
$src_path = $srcPath;
$image = $srcPath;
//创建图片的实例
$dst = imagecreatefromstring(file_get_contents($dst_path));
$src = imagecreatefromstring(file_get_contents($src_path));
//获取水印图片的宽高
list($src_w,$src_h) = getimagesize($src_path);
$dstImage = imagecreatetruecolor($src_w,$src_h);
//如果水印图片本身带透明色,则使用imagecopy方法
imagecopy($dst, $src, 85,85, 0, 0, $src_w, $src_h);
//输出图片
list($src_w, $src_h, $dst_type) = getimagesize($dst_path);
// imagejpeg($dst,".".$image);
$judge = imagejpeg($dst, $image, 90);
imagedestroy($dst);
imagedestroy($src);
if($judge){
return $image;
}else{
return false;
}
}
1、采用php自有的压缩,不支持png格式图片进行压缩,所以需要先转换为jpg格式,这段代码有点问题,建议仅做参考
/**
* png 转化为jpg格式的图片
* @param $srcPathName 要转换的图片的地址
* @param bool|true $delOri
* @return mixed
*/
public function pngTojpg($srcPathName, $delOri=true)
{
$srcFile = $srcPathName;
//1.图片格式替换
$dstFile = str_replace('.png', '.jpg', $srcFile);//图片格式后缀替换
$photoSize = getimagesize($srcFile);//获取图片的大小信息
$pw = $photoSize[0];//宽度
$ph = $photoSize[1];//高度
$dstImage = ImageCreateTrueColor($pw, $ph);
//2.上色
$color=imagecolorallocate($dstImage,255,255,255);
//3.设置透明
imagecolortransparent($dstImage,$color);
imagefill($dstImage,0,0,$color);
//4.读取图片
$srcImage = imagecreatefrompng($srcFile);
imagesavealpha($srcImage,true);//这里很重要;
//5.合拼图片
imagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, $pw, $ph, $pw, $ph);
imagejpeg($dstImage, $dstFile, 0);
if ($delOri)
{
unlink($srcFile);
}
imagedestroy($srcImage);
imagedestroy($dstImage);
$srcFile=$dstFile;
return $srcFile;
}
imagecopyresized
函数用于拷贝图像或图像的一部分并调整大小,成功返回 TRUE ,否则返回 FALSE 。
所生成的图像比较粗糙,但是速度较快
imagecopyresampled
是GD 2.x后新增加的函数,字面上的意思是会对图片进行重新采样(resampling),GD是采用插值算法生成更平滑的图像。
图片质量更高,但是速度较慢