php合成两张图片且限制第二张图片的尺寸
代码如下:<?php
// 创建空白画布
$canvasWidth = 400; // 画布宽度
$canvasHeight = 300; // 画布高度
$canvas = imagecreatetruecolor($canvasWidth, $canvasHeight);
// 背景颜色(可选)
$backgroundColor = imagecolorallocate($canvas, 255, 255, 255); // 白色
imagefill($canvas, 0, 0, $backgroundColor);
// 加载第一张图片
$image1Path = 'image1.jpg'; // 你的第一张图片路径
$image1 = imagecreatefromjpeg($image1Path);
// 获取第一张图片的尺寸
$image1Width = imagesx($image1);
$image1Height = imagesy($image1);
// 限制第一张图片的尺寸
$maxImage1Width = 400;
$maxImage1Height = 300;
if ($image1Width > $maxImage1Width || $image1Height > $maxImage1Height) {
$ratio = min($maxImage1Width / $image1Width, $maxImage1Height / $image1Height);
$newWidth = $image1Width * $ratio;
$newHeight = $image1Height * $ratio;
$resizedImage1 = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($resizedImage1, $image1, 0, 0, 0, 0, $newWidth, $newHeight, $image1Width, $image1Height);
// 合成第一张缩放后的图片到画布
imagecopy($canvas, $resizedImage1, 0, 0, 0, 0, $newWidth, $newHeight);
} else {
// 合成原始尺寸的第一张图片到画布
imagecopy($canvas, $image1, 0, 0, 0, 0, $image1Width, $image1Height);
}
// 加载第二张图片
$image2Path = 'image2.jpg'; // 你的第二张图片路径
$image2 = imagecreatefromjpeg($image2Path);
// 获取第二张图片的尺寸
$image2Width = imagesx($image2);
$image2Height = imagesy($image2);
// 限制第二张图片的尺寸
$maxImage2Width = 200;
$maxImage2Height = 150;
if ($image2Width > $maxImage2Width || $image2Height > $maxImage2Height) {
$ratio = min($maxImage2Width / $image2Width, $maxImage2Height / $image2Height);
$newWidth = $image2Width * $ratio;
$newHeight = $image2Height * $ratio;
$resizedImage2 = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($resizedImage2, $image2, 0, 0, 0, 0, $newWidth, $newHeight, $image2Width, $image2Height);
// 合成第二张缩放后的图片到画布
imagecopy($canvas, $resizedImage2, $canvasWidth - $newWidth, $canvasHeight - $newHeight, 0, 0, $newWidth, $newHeight);
} else {
// 合成原始尺寸的第二张图片到画布
imagecopy($canvas, $image2, $canvasWidth - $image2Width, $canvasHeight - $image2Height, 0, 0, $image2Width, $image2Height);
}
// 输出合成后的图片
header('Content-Type: image/jpeg');
imagejpeg($canvas, 'output.jpg'); // 输出到文件或直接显示
// 释放资源
imagedestroy($canvas);
imagedestroy($image1);
imagedestroy($image2);
?>
页:
[1]