1.图片背景管理
使用 imagecreate()和 imagecreatetruecolor()函数可以创建画布资源。但如果已经拥有图片进行处理,只需要将这个图片作为画布资源即可,也就是我们所说的创建图片背景。
imagecreatefromjpeg($path)
imagecreatefrompng($path)
imagecreatefromgif($path)
获取图片类型宽度高度等 getimagesize($path)
2.图片放缩
imagecopyresampled(dst_img,src_img,dst_x,dst_y,src_x,src_y,dst_w,dst_h,src_w,src_h)
自定义图像放缩函数:
function thumb($filename,$width=200,$height=200){
//获取原图像的宽和高
list($width_orig,$height_orig)=getimagesize($filename);
//换算出比例宽高
if($width && ($width_orig<$height_orig)){
$width=($height/$height_orig)*$width_orig;
}else{
$height=($width/$width_orig)*$height_orig;
}
$im=imagecreatetruecolor($width,$height);
$image=imagecreatefromjpeg($filename);//放缩jpeg格式
imagecopyresampled($im,$image,0,0,0,0,$width,$height,$width_orig,$height_orig);
imagejpeg($im,$filename,100);
imagedestroy($im);
imagedestroy($image);
}
3.图片裁剪
自定义裁剪函数:
function cut($filename,$x,$y,$width,$height){
//创建背景资源
$back=imagecreatefromjpeg($filename);
//创建保存裁剪后资源
$im=imagecreatetruecolor($width,$height);
//裁剪
imagecopyresampled($im,$back,0,0,$x,$y,$width,$height,$width,$height);
//覆盖原图,如果不想覆盖可加前缀
imagejpeg($im,$filename);
imagedestroy($im);
imagedestroy($back);
4.添加水印
自定义水印函数:
function watermark($filename,$water){
//获取背景图的宽高
list($b_w,$b_h)=getimagesize($filename);
//获取水印的宽高
list($w_w,$w_h)=getimagesize($water);
//水印在背景图的随机位置
$posx=rand(0,($b_w-$w_w));
$posy=rand(0,($b_h-$w_h));
//创建背景和水印资源
$back=imagecreatefromjpeg($filename);
$water=imagecreatefrompng($water);
//添加水印
imagecopy($back,$water,$posx,$posy,0,0,$w_w,$w_h);
//保存水印图
imagejpeg($back,$filename);
//释放资源
imagedestroy($water);
imagedestroy($back);
}5.图片旋转
自定义旋转函数:
function rotate($filename,$degrees){
//创建图像资源
$im=imagecreatefromjpeg($filename);
//按指定角度旋转
$rotate=imagerotate($im,$degrees,0);
//保存旋转后图
imagejpeg($im,$filename);
}