Return to Snippet

Revision: 12464
at March 16, 2009 09:00 by eden159


Initial Code
<?php

function mergeImages($images) {
	$imageData = array();
	$len = count($images);
	$wc = ceil(sqrt($len));
	$hc = floor(sqrt($len/2));
	$maxW = array();
	$maxH = array();
	for($i = 0; $i < $len; $i++) {
		$imageData[$i] = getimagesize($images[$i]);
		$found = false;
		for($j = 0; $j < $i; $j++) {
			if ( $imageData[$maxW[$j]][0] < $imageData[$i][0] ) {
				$farr = $j > 0 ? array_slice($maxW, $j-1, $i) : array();
				$maxW = array_merge($farr, array($i), array_slice($maxW, $j));
				$found = true;
				break;
			}
		}
		if ( !$found ) {
			$maxW[$i] = $i;
		}
		$found = false;
		for($j = 0; $j < $i; $j++) {
			if ( $imageData[$maxH[$j]][1] < $imageData[$i][1] ) {
				$farr = $j > 0 ? array_slice($maxH, $j-1, $i) : array();
				$maxH = array_merge($farr, array($i), array_slice($maxH, $j));
				$found = true;
				break;
			}
		}
		if ( !$found ) {
			$maxH[$i] = $i;
		}
	}
	
	$width = 0;
	for($i = 0; $i < $wc; $i++) {
		$width += $imageData[$maxW[$i]][0];
	}
	
	$height = 0;
	for($i = 0; $i < $hc; $i++) {
		$height += $imageData[$maxH[$i]][1];
	}

	$im = imagecreatetruecolor($width, $height);
	
	$wCnt = 0;
	$startWFrom = 0;
	$startHFrom = 0;
	for( $i = 0; $i < $len; $i++ ) {
		$tmp = imagecreatefromjpeg($images[$i]);
		imagecopyresampled($im, $tmp, $startWFrom, $startHFrom, 0, 0, $imageData[$i][0], $imageData[$i][1], $imageData[$i][0], $imageData[$i][1]);
		$wCnt++;
		if ( $wCnt == $wc ) {
			$startWFrom = 0;
			$startHFrom += $imageData[$maxH[0]][1];
			$wCnt = 0;
		} else {
			$startWFrom += $imageData[$i][0];
		}
	}
	
	
	return $im;
}

$im = mergeImages(array('1.jpg', '2.jpg'));

header('Content-type: image/jpg');

imagejpeg($im);

?>

Initial URL

                                

Initial Description

                                

Initial Title
Merge 2 or more images into one

Initial Tags
php, images

Initial Language
PHP