查看: 915|回复: 0

php合成两张图片且限制第二张图片的尺寸

[复制链接]

748

主题

39

回帖

3907

积分

管理员

总舵主

积分
3907
QQ
发表于 2024-1-12 22:16:25 | 显示全部楼层 |阅读模式
代码如下:

  1. <?php
  2. // 创建空白画布
  3. $canvasWidth = 400; // 画布宽度
  4. $canvasHeight = 300; // 画布高度
  5. $canvas = imagecreatetruecolor($canvasWidth, $canvasHeight);

  6. // 背景颜色(可选)
  7. $backgroundColor = imagecolorallocate($canvas, 255, 255, 255); // 白色
  8. imagefill($canvas, 0, 0, $backgroundColor);

  9. // 加载第一张图片
  10. $image1Path = 'image1.jpg'; // 你的第一张图片路径
  11. $image1 = imagecreatefromjpeg($image1Path);

  12. // 获取第一张图片的尺寸
  13. $image1Width = imagesx($image1);
  14. $image1Height = imagesy($image1);

  15. // 限制第一张图片的尺寸
  16. $maxImage1Width = 400;
  17. $maxImage1Height = 300;

  18. if ($image1Width > $maxImage1Width || $image1Height > $maxImage1Height) {
  19.     $ratio = min($maxImage1Width / $image1Width, $maxImage1Height / $image1Height);
  20.     $newWidth = $image1Width * $ratio;
  21.     $newHeight = $image1Height * $ratio;

  22.     $resizedImage1 = imagecreatetruecolor($newWidth, $newHeight);
  23.     imagecopyresampled($resizedImage1, $image1, 0, 0, 0, 0, $newWidth, $newHeight, $image1Width, $image1Height);

  24.     // 合成第一张缩放后的图片到画布
  25.     imagecopy($canvas, $resizedImage1, 0, 0, 0, 0, $newWidth, $newHeight);
  26. } else {
  27.     // 合成原始尺寸的第一张图片到画布
  28.     imagecopy($canvas, $image1, 0, 0, 0, 0, $image1Width, $image1Height);
  29. }

  30. // 加载第二张图片
  31. $image2Path = 'image2.jpg'; // 你的第二张图片路径
  32. $image2 = imagecreatefromjpeg($image2Path);

  33. // 获取第二张图片的尺寸
  34. $image2Width = imagesx($image2);
  35. $image2Height = imagesy($image2);

  36. // 限制第二张图片的尺寸
  37. $maxImage2Width = 200;
  38. $maxImage2Height = 150;

  39. if ($image2Width > $maxImage2Width || $image2Height > $maxImage2Height) {
  40.     $ratio = min($maxImage2Width / $image2Width, $maxImage2Height / $image2Height);
  41.     $newWidth = $image2Width * $ratio;
  42.     $newHeight = $image2Height * $ratio;

  43.     $resizedImage2 = imagecreatetruecolor($newWidth, $newHeight);
  44.     imagecopyresampled($resizedImage2, $image2, 0, 0, 0, 0, $newWidth, $newHeight, $image2Width, $image2Height);

  45.     // 合成第二张缩放后的图片到画布
  46.     imagecopy($canvas, $resizedImage2, $canvasWidth - $newWidth, $canvasHeight - $newHeight, 0, 0, $newWidth, $newHeight);
  47. } else {
  48.     // 合成原始尺寸的第二张图片到画布
  49.     imagecopy($canvas, $image2, $canvasWidth - $image2Width, $canvasHeight - $image2Height, 0, 0, $image2Width, $image2Height);
  50. }

  51. // 输出合成后的图片
  52. header('Content-Type: image/jpeg');
  53. imagejpeg($canvas, 'output.jpg'); // 输出到文件或直接显示

  54. // 释放资源
  55. imagedestroy($canvas);
  56. imagedestroy($image1);
  57. imagedestroy($image2);
  58. ?>
复制代码


道不同,不相为谋!理想要有,万一实现了呢?
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注公众号

相关侵权、举报、投诉及建议等,请发 E-mail:2513533699@qq.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.|鲁ICP备19000917号|鲁公网安备37078302000320号

在本版发帖
关注公众号
QQ客服返回顶部