将多张图片,按照规格合成一张图片。
public function mergeImage($imgUrls, $saveLocalPath)
{
$result = ['code' => 400, 'msg' => '参数错误', 'data' => []];
if (empty($imgUrls) || !is_array($imgUrls)) {
return $result;
}
ini_set('memory_limit', '256M');
ini_set('memory_limit', '-1');
// 因为上传的图片可能有大有小,所有我们这里定义一个统一的宽度,保证拼接的时候图片会比较美观
$maxWidth = 1000;//设置画布的最大宽
// 处理后图片数据的集合
$imgObjList = array();
// 拼接后图片最终的高度
$imgHeight = 0;
foreach ($imgUrls as $img) {
$path = $img;
// 判别图像文件的类型
$image = exif_imagetype($path);
// 将图像类型常量转换成图片文件的MIME类型
$mime_type = image_type_to_mime_type($image); //获取文件真实的mime类型
if ($mime_type == 'image/png') {
// 由文件或 URL 创建一个新图象。
$imageObj = imagecreatefrompng($path);
} else if ($mime_type == 'image/jpeg') {
$imageObj = imagecreatefromjpeg($path);
} else {
$imageObj = imagecreatefromjpeg($path);
}
// 获取图像的宽度
$imgWidth = imagesx($imageObj);
// 用最大宽度 除以 图片真实宽度,得到宽度比例
$rate = $maxWidth / $imgWidth;
// 获取图像的高度
$oldHeight = imagesy($imageObj);
// 用图像真实高度 乘以 宽度比例 等于 修改后的图像高度
$newHeight = floor($oldHeight * $rate);
// 累加计算拼接后图像高度
$imgHeight += $newHeight;
$data = [];
$data['maxHeight'] = $newHeight;
$data['obj'] = $imageObj;
// 插入图像信息
$imgObjList[] = $data;
}
// 根据最终高度和宽度得到空白画布
$imageBk = imagecreatetruecolor($maxWidth, $imgHeight);
// 为真彩画布创建白色背景
$color = imagecolorallocate($imageBk, 255, 255, 255);
imagefill($imageBk, 0, 0, $color);
// 设置透明
imageColorTransparent($imageBk, $color);
$imageY = 0;
foreach ($imgObjList as $imgItem) {
// 拼接图片,
imagecopyresampled($imageBk, $imgItem['obj'], 0, $imageY, 0, 0, $maxWidth, $imgItem['maxHeight'], imagesx($imgItem['obj']), imagesy($imgItem['obj']));
$imageY += $imgItem['maxHeight'];
}
$upload_path = $_SERVER['DOCUMENT_ROOT'] . $saveLocalPath;//保存的文件路径绝对路径
if (!is_dir($upload_path)) {
mkdir($upload_path, 0755, true);
}
$file_path = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $saveLocalPath;//返回的文件路径
$newFileName = uniqid() . '.png';
$newImgLink = $saveLocalPath . $newFileName;//文件地址
// 输出合成图片
if (imagejpeg($imageBk, "." . $newImgLink)) {
$result['code'] = 200;
$result['msg'] = '保存成功';
$result['data']['imagePath'] = $newImgLink;
$result['data']['imageAbsolutePath'] = $file_path . $newFileName; //完整的路径;
$result['data']['time'] = date('Y-m-d H:i:s');
} else {
$result['code'] = 0;
$result['msg'] = '保存失败';
}
return $result;
}