PHP - 从多张图片创建一张图片

5

我有n张图片并希望使用PHP代码创建一张合并后的图片。我尝试使用imagecopymerge()函数,但是无法实现。请给出一些示例。


6
请发布您尝试过的内容。 - Nadh
请参见此处:https://dev59.com/OnM_5IYBdhLWcg3wZSTX。 - endo.anaconda
如果您想复制并调整图像大小,请按照以下教程操作:http://blog.webtech11.com/2012/04/21/upload-and-resize-an-image-with-php.html - jogesh_pi
2个回答

7

代码:

$numberOfImages = 3;
$x = 940;
$y = 420;
$background = imagecreatetruecolor($x, $y*3);


$firstUrl = '/images/upload/photoalbum/photo/1.jpg';

$secondUrl = '/images/upload/photoalbum/photo/2.jpg';

$thirdUrl = '/images/upload/photoalbum/photo/3.jpg';

$outputImage = $background;

$first = imagecreatefromjpeg($firstUrl);
$second = imagecreatefromjpeg($secondUrl);
$third = imagecreatefromjpeg($thirdUrl);



imagecopymerge($outputImage,$first,0,0,0,0, $x, $y,100);
imagecopymerge($outputImage,$second,0,$y,0,0, $x, $y,100);
imagecopymerge($outputImage,$third,0,$y*2,0,0, $x, $y,100);

imagejpeg($outputImage, APPLICATION_PATH .'/images/upload/photoalbum/photo/test.jpg');

imagedestroy($outputImage);

3

感谢kruksmail,

我根据你的答案调整了特定项目中可能不知道图片的情况。所以我让你的答案适用于一组图像。

它还可以指定你想要多少行或列。我也添加了一些注释来帮助理解。

$images = array('/images/upload/photoalbum/photo/1.jpg','/images/upload/photoalbum/photo/2.jpg','/images/upload/photoalbum/photo/3.jpg');
$number_of_images = count($images);

$priority = "columns"; // also "rows"

if($priority == "rows"){
  $rows = 3;
  $columns = $number_of_images/$rows;
  $columns = (int) $columns; // typecast to int. and makes sure grid is even
}else if($priority == "columns"){
  $columns = 3;
  $rows = $number_of_images/$columns;
  $rows = (int) $rows; // typecast to int. and makes sure grid is even
}
$width = 150; // image width
$height = 150; // image height

$background = imagecreatetruecolor(($width*$columns), ($height*$rows)); // setting canvas size
$output_image = $background;

// Creating image objects
$image_objects = array();
for($i = 0; $i < ($rows * $columns); $i++){
  $image_objects[$i] = imagecreatefromjpeg($images[$i]);
}

// Merge Images
$step = 0;
for($x = 0; $x < $columns; $x++){
  for($y = 0; $y < $rows; $y++){
    imagecopymerge($output_image, $image_objects[$step], ($width * $x), ($height * $y), 0, 0, $width, $height, 100);
    $step++; // steps through the $image_objects array
  }
}

imagejpeg($output_image, 'test.jpg');
imagedestroy($output_image);

print "<div><img src='test.jpg' /></div>";

谢谢您,我能够根据这个来解决我遇到的问题。 - Dominic Williams
2.5年来一直很有帮助。谢谢!如果您想将图像从中心裁剪在一起而不是从左侧边缘开始,请将imagecopymerge()方法修改为以下内容:imagecopymerge($output_image, $image_objects[$step], ($width * $x), ($height * $y), imagesx($image_objects[$step])/2 - $width/2, 0, $width, $height, 100); - justinl
仍然在2022年有用 ;) 如果你想调整(并适应)源图像的大小(而不是裁剪它们),可以使用imagecopyresampled,像这样:imagecopyresampled($output_image, $image_objects[$step], ($width * $x), ($height * $y), 0, 0, $width, $height, imagesx($image_objects[$step]), imagesy($image_objects[$step])); - Cédric

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接