Merge two images in php

廉价感情. 提交于 2019-11-27 14:14:26

The best approach for this situation may be to create a new image in memory with the combined dimensions you desire, then copy or resample the existing images to the new image, and then save the new image to disk.

For example:

function merge($filename_x, $filename_y, $filename_result) {

 // Get dimensions for specified images

 list($width_x, $height_x) = getimagesize($filename_x);
 list($width_y, $height_y) = getimagesize($filename_y);

 // Create new image with desired dimensions

 $image = imagecreatetruecolor($width_x + $width_y, $height_x);

 // Load images and then copy to destination image

 $image_x = imagecreatefromjpeg($filename_x);
 $image_y = imagecreatefromgif($filename_y);

 imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
 imagecopy($image, $image_y, $width_x, 0, 0, 0, $width_y, $height_y);

 // Save the resulting image to disk (as JPEG)

 imagejpeg($image, $filename_result);

 // Clean up

 imagedestroy($image);
 imagedestroy($image_x);
 imagedestroy($image_y);

}

Example:

merge('images/myimg.jpg', 'images/second.gif', 'images/merged.jpg');

I suggest you to use Image Magick instead (pecl-imagick module or running it as command via shell). I have several reasons:

Imagick is:

  • faster
  • knows more format
  • makes better quality images
  • have more ability (for example text rotation)
  • and more...

Your method is Imagick::compositeImage if you use the php module. Manual: http://php.net/manual/en/function.imagick-compositeimage.php

Avinash singh

i would like to add one more thing here if you are using PHP GD Library,then you should include imagesavealpha() and alphablending() also.

I found the answer, use GD:

 function merge($filename_x, $filename_y, $filename_result) {

 // Get dimensions for specified images

 list($width_x, $height_x) = getimagesize($filename_x);
 list($width_y, $height_y) = getimagesize($filename_y);

 // Create new image with desired dimensions

 $image = imagecreatetruecolor($width_x, $height_x);

 // Load images and then copy to destination image

 $image_x = imagecreatefromjpeg($filename_x);
 $image_y = imagecreatefromgif($filename_y);

 imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
                        //  top, left, border,border
 imagecopy($image, $image_y, 100, 3100, 0, 0, $width_y, $height_y);

 // Save the resulting image to disk (as JPEG)

 imagejpeg($image, $filename_result);

 // Clean up

 imagedestroy($image);
 imagedestroy($image_x);
 imagedestroy($image_y);

}

like this:

merge('images/myimage.jpg', 'images/second.gif', 'images/merged.jpg');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!