欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

php合并图片,

程序员文章站 2022-04-26 22:32:25
...

php合并图片,

在项目中需要把几张图片合并在一起,如下图

分别由头、身、腿三张图片合并起来

代码如下:

 1 function combineImage($head_img,$middle_img,$footer_img,$save_path){
 2     $source_w = 400;
 3     $source_h = 1142;
 4     //取头部图片大小
 5     $head_size = getimagesize($head_img);
 6     $head_height = $head_size['1'];
 7     $head_width = $head_size['0'];
 8     $head_start_x = floor(($source_w-$head_width)/2);//头部开始位置
 9     //取中间图片大小
10     $midd_size = getimagesize($middle_img);
11     $midd_height = $midd_size['1'];
12     $midd_width = $midd_size['0'];
13     $midd_start_y = $head_height-15;//中间开始Y坐标,因为头部的图片底部有空白,所以减去15
14     $midd_start_x = floor(($source_w-$midd_width)/2);
15     
16     //取底部图片大小
17     $foot_size = getimagesize($footer_img);
18     $foot_height = $foot_size[1];
19     $foot_width = $foot_size[0];
20     $foot_start_x = floor(($source_w-$foot_width)/2);//底部图片x坐标
21     $foot_start_y = $source_h-$foot_height;//底部图片y坐标
22     
23     $head = imagecreatefrompng($head_img);
24     $middle = imagecreatefrompng($middle_img);
25     $footer = imagecreatefrompng($footer_img);
26     
27     $bg_img = imageCreatetruecolor($source_w,$source_h);//生成背景图片
28     $color = imagecolorallocate($bg_img, 255, 255, 255); //设置白色背景
29     imagefill($bg_img, 0, 0, $color);//背景色填充
30     imageColorTransparent($bg_img, $color);//透明
31     imagecopyresampled($bg_img,$head,$head_start_x,0,0,0,$head_width,$head_height,$head_width,$head_height);
32     imagecopyresampled($bg_img,$middle,$midd_start_x , $midd_start_y,0,0,$midd_width,$midd_height,$midd_width,$midd_height);
33     imagecopyresampled($bg_img,$footer,$foot_start_x , $foot_start_y,0,0,$foot_width,$foot_height,$foot_width,$foot_height);
34     
35     imagepng($bg_img,$save_path );
36 }
37 $head = dirname(__FILE__).'/public/images/head.png';
38 $midd = dirname(__FILE__).'/public/images/midd1.png';
39 $foot = dirname(__FILE__).'/public/images/foot1.png';
40 $save_path = dirname(__FILE__)."/public/images/testcomblie.png";
41 combineImage($head,$midd,$foot,$save_path);