使用PHP合并多张图像
项目中,需要将用户上传的身份证正面和背面合成到一张A4纸上。所以,涉及到PHP图像处理这一块,简单记录一下。
主要的方法是使用PHP自带的GD图像库,需要用到如下几个函数
- imagecreatetruecolor => 新建一个真彩色图像
- imagecolorallocate => 为一幅图像分配颜色
- imagefill => 填充图像
- getimagesize => 获取图像的基础信息,大小,类型等
getimagesize返回一个数组 [0] => 525 宽度 [1] => 311 高度 [2] => 2 文件类型{1=GIF, 2=JPG, 3=PNG, 4=SWF, 5=PSD, 6=BMP} [3] => width="525" height="311" 宽高的字符串 [bits] => 8 [channels] => 3 [mime] => image/jpeg
- imagecreatefromjpeg => 从一张jpeg图像创建一个资源对象
- imagecopyresampled => 重采样拷贝部分图像并调整大小
- imagecopy => 拷贝图像的一部分
- imagepng => 根据图像对象生成png图片
A4纸对应的像素如下:
分辨率是72像素/英寸,A4纸的像素是595×842,
分辨率是150像素/英寸,A4纸的像素是1240×1754,
分辨率是300像素/英寸,A4纸的像素是2479×3508,
实际Demo看了一下,A4纸的像素是2480 * 3508
。对应的身份证的像素是210×297
。
所以,这里,当用户上传身份证正反两面之后,需要处理两个流程:缩放,合并。
最后的代码示例如下
<?php
public static function mergeImagesIntoA4($src = [], $dstFile = 'demo.png') {
// 定义A4纸的尺寸
$width = 2480;
$height = 3508;
// 定义身份证的尺寸
$identityWidth = 1014;
$dstImage = imagecreatetruecolor($width, $height); // 创建一个A4纸的图像
$color = imagecolorallocate($dstImage, 255,255,255); // 定义填充的颜色为白色
imagefill($dstImage,0,0,$color); // 进行填充
// 身份证摆放的坐标点,左上角为0*0
$locX = 700;
$locY = 700;
foreach ($src as $v) {
// 获取图片的信息
$info = getimagesize($v);
$imgWidth = $info[0];
$imgHeight = $info[1];
// 缩放之后的高度
$identityHeight = ($identityWidth/$imgWidth)*$imgHeight;
// 创建身份证图片
$im = imagecreatetruecolor($identityWidth, $identityHeight);
switch($info[2]) {
case 2:
$identityImage = imagecreatefromjpeg($v);
break;
case 3:
$identityImage = imagecreatefrompng($v);
break;
default:return false;break;
}
imagecopyresampled($im, $identityImage, 0, 0, 0, 0, $identityWidth, $identityHeight, $imgWidth, $imgHeight);
// 合并到背景上
imagecopy($dstImage, $im, $locX, $locY, 0, 0, $identityWidth, $identityHeight);
// 设置偏移
$locY += $identityHeight + 300;
}
// 输出文件
imagepng($dstImage, $dstFile);
}
最后效果
就是这样子。
··· 完 ···
版权声明: 本博客所有文章除特别声明外,均采用CC BY-NC-SA 3.0许可协议,转载请注明出处。