barinbritva
12/5/2013 - 11:09 AM

Image resizing with possibility fixed canvas size (empty space fills white color)

Image resizing with possibility fixed canvas size (empty space fills white color)

<?php
function resizeImage($outfile, $infile, $neww, $newh, $quality, $fillArea=false)
{
	$imageInfo = getimagesize($infile);

	switch($imageInfo['mime'])
	{
		case 'image/jpeg':
		case 'image/jpg':
			$im=imagecreatefromjpeg($infile);
		break;
		case 'image/png':
			$im = imagecreatefrompng($infile);
		break;
		case 'image/gif':
			$im = imagecreatefromgif($infile);
		break;

		default:
			return false;
		break;
	}


	$k1=$neww/imagesx($im);
	$k2=$newh/imagesy($im);

	if ($k1>$k2)
	{
		$k = $k2;
		$layout = 'y';
	}
	else
	{
		$k = $k1;
		$layout = 'x';
	}

	$w=intval(imagesx($im)*$k);
	$h=intval(imagesy($im)*$k);

	if ($fillArea)
	{
		$im1=imagecreatetruecolor($neww, $newh);
		if ($layout=='x')
		{
			$marginX = 0;
			$marginY = intval(($newh-$h)/2);
		}
		else
		{
			$marginX = intval(($neww-$w)/2);
			$marginY = 0;
		}
	}
	else
	{
		$im1=imagecreatetruecolor($w, $h);
		$marginX = $marginY = 0;
	}

	$white = imagecolorallocate($im1, 255, 255, 255);
	imagefill($im1, 0, 0, $white);

	imagecopyresampled($im1, $im, $marginX, $marginY, 0, 0, $w, $h, imagesx($im), imagesy($im));

	imagejpeg($im1, $outfile, $quality);
	imagedestroy($im);
	imagedestroy($im1);
	return true;
}