Merge 2 or more images into one


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. function mergeImages($images) {
  4. $imageData = array();
  5. $len = count($images);
  6. $wc = ceil(sqrt($len));
  7. $hc = floor(sqrt($len/2));
  8. $maxW = array();
  9. $maxH = array();
  10. for($i = 0; $i < $len; $i++) {
  11. $imageData[$i] = getimagesize($images[$i]);
  12. $found = false;
  13. for($j = 0; $j < $i; $j++) {
  14. if ( $imageData[$maxW[$j]][0] < $imageData[$i][0] ) {
  15. $farr = $j > 0 ? array_slice($maxW, $j-1, $i) : array();
  16. $maxW = array_merge($farr, array($i), array_slice($maxW, $j));
  17. $found = true;
  18. break;
  19. }
  20. }
  21. if ( !$found ) {
  22. $maxW[$i] = $i;
  23. }
  24. $found = false;
  25. for($j = 0; $j < $i; $j++) {
  26. if ( $imageData[$maxH[$j]][1] < $imageData[$i][1] ) {
  27. $farr = $j > 0 ? array_slice($maxH, $j-1, $i) : array();
  28. $maxH = array_merge($farr, array($i), array_slice($maxH, $j));
  29. $found = true;
  30. break;
  31. }
  32. }
  33. if ( !$found ) {
  34. $maxH[$i] = $i;
  35. }
  36. }
  37.  
  38. $width = 0;
  39. for($i = 0; $i < $wc; $i++) {
  40. $width += $imageData[$maxW[$i]][0];
  41. }
  42.  
  43. $height = 0;
  44. for($i = 0; $i < $hc; $i++) {
  45. $height += $imageData[$maxH[$i]][1];
  46. }
  47.  
  48. $im = imagecreatetruecolor($width, $height);
  49.  
  50. $wCnt = 0;
  51. $startWFrom = 0;
  52. $startHFrom = 0;
  53. for( $i = 0; $i < $len; $i++ ) {
  54. $tmp = imagecreatefromjpeg($images[$i]);
  55. imagecopyresampled($im, $tmp, $startWFrom, $startHFrom, 0, 0, $imageData[$i][0], $imageData[$i][1], $imageData[$i][0], $imageData[$i][1]);
  56. $wCnt++;
  57. if ( $wCnt == $wc ) {
  58. $startWFrom = 0;
  59. $startHFrom += $imageData[$maxH[0]][1];
  60. $wCnt = 0;
  61. } else {
  62. $startWFrom += $imageData[$i][0];
  63. }
  64. }
  65.  
  66.  
  67. return $im;
  68. }
  69.  
  70. $im = mergeImages(array('1.jpg', '2.jpg'));
  71.  
  72. header('Content-type: image/jpg');
  73.  
  74. imagejpeg($im);
  75.  
  76. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.