php合成图片加水印

分享自己写的一个php的图像处理的一些方法,包括图片的缩小和放大,两张图的合成,和图片写入文字

这里实现的是一个底图和一个二维码合成并加上水印的功能,其中二维码可以自定义缩放比例

先是生成一个底图画布,然后生成相关大小的二维码图片的临时文件,然后将两张图合成,最后在画布上写入文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
/**
* author lkj
* date 2015/12/26
* @param string $img 底图路径
* @param string $qrcode 二维码路径
* @param int $x 二维码左边距 true水平居中
* @param int $y 二维码上边距 true垂直居中
* @param int $percent 二维码按比例缩放
* @param bool $save false直接输出true保存文件
*/

/**
bool imagecopy ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h )
将 src_im 图像中坐标从 src_x,src_y 开始,宽度为 src_w,高度为 src_h 的一部分拷贝到 dst_im 图像中坐标为 dst_x 和 dst_y 的位置上。
*/

function mergerImg($img, $qrcode, $x, $y, $percent, $save = false)
{
/***底图处理****/
list($max_width, $max_height) = getimagesize($img);
$dests = imagecreatetruecolor($max_width, $max_height);
$dst_im = imagecreatefromjpeg($img);
imagecopy($dests, $dst_im, 0, 0, 0, 0, $max_width, $max_height);
imagedestroy($dst_im);

/*********二维码大小调整并保存********** */
// Get new sizes
list($width, $height) = getimagesize($qrcode);

$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefrompng($qrcode);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$name = 'tmep.png';//缩放二维码存放临时文件
// Save
imagepng($thumb, $name);

/*******图片合成*********/
$src_im = imagecreatefrompng($name);
$src_info = getimagesize($name);

if ($x === true) {//水平居中
$padding_left = ($max_width - $src_info[0]) / 2;
} else {
$padding_left = $x;
}
if ($y === true) {//垂直居中
$padding_top = ($max_height - $src_info[1]) / 2;
} else {
$padding_top = $y;
}
imagecopy($dests, $src_im, $padding_left, $padding_top, 0, 0, $src_info[0], $src_info[1]);

/*******写入文字******/
$color = imagecolorallocate($dests, 255, 255, 255); //字体颜色
$fontfile = "font.ttf"; //字体文件
$string = "@likangjun.com";
imagettftext($dests, 18, 0, 230, 760, $color, $fontfile, $string);
unlink($name);//删除临时文件

/*******保存文件********/
if ($save) {
$savepath = "qrcode.png";
$result = imagepng($dests, $savepath);
imagedestroy($dests);
echo $result ? 'success' : 'fail';
}

/*******输出到浏览器********/
header('Content-Type: image/jpeg');
imagepng($dests);
imagedestroy($dests);
}

相关的小项目可以看githu和demo更加的直观
demo用get自定义二维码内容和水印内容,不妨点击去试试~
github的地址是:https://github.com/likangjun/image
demo: http://demo.likangjun.com/image/index.php?qrcode=http://likangjun.com&water=likangjun.com