[Toc]
一、图片水印
1、实现步骤
- 打开原图(也叫操作的目标图片)
- 打开水印图(也叫水印来源图片)
- 使用 imagecopymerge 将小图合并至大图的指定位置
- 输出图片
- 销毁资源
2、实例代码
$dst_path = 'image/meinv.jpg';
$dst = imagecreatefromstring(file_get_contents($dst_path));
$logo_path = 'image/jack.jpg';
$logo = imagecreatefromstring(file_get_contents($logo_path));
list($dst_width,$dst_height) = getimagesize($dst_path);
list($logo_width,$logo_height) = getimagesize($logo_path);
$dst_x = $dst_width - $logo_width;
$dst_y = $dst_height - $logo_height;
//要将图片加在右下脚
imagecopymerge($dst, $logo, $dst_x, $dst_y, 0, 0, $logo_width, $logo_height, 50);
header('Content-type:image/png');
imagepng($dst);
imagedestroy($dst);
二、文字水印
/**
* imagecolorallocatealpha() 的行为和 imagecolorallocate() 相同,
* 但多了一个额外的透明度参数 alpha,其值从 0 到 127。0 表示完全不透明,127 表示完全透明。
*/
$filename = 'image/meinv.jpg';
$fileinfo = getimagesize($filename);
list( $width, $height ) = $fileinfo;
$mime = $fileinfo['mime'];
$createFrom = str_replace('/','createfrom',$mime);
$outFun = str_replace('/','',$mime);
$image = $createFrom($filename);
$color = imagecolorallocatealpha($image, 255, 0, 0, 80);
imagettftext($image, 30, 0, 0,ceil(($height-30)/2), $color, 'fonts/SIMSUN.TTC', 'Jack喜欢的妞');
header('content-type:'.$mime);
$outFun($image);
imagedestroy($image);
三、验证码
function createCheckCode( $codeNum ){ $code="23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ";
$string='';
//从字符串中取出随机的字符
for($i=0; $i < $codeNum; $i++){
$char=$code{mt_rand(0, strlen($code)-1)};
$string.=$char;
}
//返回字符内容
return $string;
}
$width = 100;
$height = 30;
# 准备画布
$image = imagecreatetruecolor($width, $height);
# 准备颜色
$color_dan = imagecolorallocate($image, 200, 200, 200);
$color_shen = imagecolorallocate($image, 2, 2, 2);
# 填充背景颜色
imagefilledrectangle($image, 0, 0, $width, $height, $color_dan);
# 将字符写入画布
$str = createCheckCode(4);
for ($i = 0; $i < 4; $i++) {
$pj = 100/4;
$startx = $i*$pj + 10;
$starty = rand(0, 30-15);
imagechar($image, 7, $startx, $starty, $str{$i}, $color_shen);
}
for ($i = 0; $i < 100; $i++) {
imagesetpixel($image, mt_rand(0, 100), mt_rand(0, 30), $color_shen);
}
# 告诉浏览器你弄了一个啥
header('Content-Type:image/png');
# 以 PNG 格式将图像输出到浏览器或文件
imagepng($image);
# 销毁 节省内存
imagedestroy($image);
四、图片缩放
- 打开来源图片
- 设置图片缩放百分比(缩放)
- 获得来源图片,按比调整大小
- 新建一个指定大小的图片为目标图
- 将来源图调整后的大小放到目标中
- 销毁资源
$src_path = 'image/meinv.jpg';
$src_image = imagecreatefromstring(file_get_contents($src_path));
list( $src_w, $src_h ) = getimagesize($src_path);
$p = 0.3;
$new_width = $src_w * $p;
$new_height = $src_h * $p;
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $src_image, 0, 0, 0, 0, $new_width, $new_height, $src_w, $src_h);
header('content-type:image/jpeg');
imagejpeg($new_image);