imagecopymerge()
是 PHP 中用于合并两个图像的函数
- 加载原始图像和目标图像:
$sourceImage = imagecreatefromjpeg('path/to/source-image.jpg'); $destinationImage = imagecreatefromjpeg('path/to/destination-image.jpg');
- 获取原始图像和目标图像的宽度和高度:
$sourceWidth = imagesx($sourceImage); $sourceHeight = imagesy($sourceImage); $destinationWidth = imagesx($destinationImage); $destinationHeight = imagesy($destinationImage);
- 计算缩放比例:
$scaleX = $destinationWidth / $sourceWidth; $scaleY = $destinationHeight / $sourceHeight;
- 使用
imagecopyresampled()
函数缩放原始图像:
$scaledImage = imagecreatetruecolor($destinationWidth, $destinationHeight); imagecopyresampled($scaledImage, $sourceImage, 0, 0, 0, 0, $destinationWidth, $destinationHeight, $sourceWidth, $sourceHeight);
- 使用
imagecopymerge()
函数将缩放后的图像合并到目标图像上:
imagecopymerge($destinationImage, $scaledImage, 0, 0, 0, 0, $destinationWidth, $destinationHeight, 100);
- 保存合并后的图像:
imagejpeg($destinationImage, 'path/to/merged-image.jpg');
- 释放内存:
imagedestroy($sourceImage); imagedestroy($destinationImage); imagedestroy($scaledImage);
将以上代码整合在一起,可以实现图像的缩放和合并功能。注意替换 ‘path/to/source-image.jpg’、‘path/to/destination-image.jpg’ 和 ‘path/to/merged-image.jpg’ 为实际的图像路径。