Monday, October 4, 2010

Resize image and set background






$filename = '/path/to/source/file/1.jpg';

// Set a maximum height and width
$width = 98;
$height = 100;

// set background color
$color_R = 0;
$color_G = 0;
$color_B = 0;

$worg=$width;
$horg=$height;

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

// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}

// Resample
$src = imagecreatetruecolor($width, $height);

$image = imagecreatefromjpeg($filename);
imagecopyresampled($src, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);


// Create image instances

$dest = imagecreatetruecolor($worg, $horg);
$mycolor = imagecolorallocate($dest, $color_R, $color_G, $color_B);
imagefill($dest, 0, 0, $mycolor);

if ($width==$worg) {$start_x=0; $start_y=round(($horg-$height)/2);}
if ($height==$horg) {$start_y=0; $start_x=round(($worg-$width)/2);}

//echo $width." ".$height." ".$worg." ".$horg."
";
//echo $start_x;
//die;

// Copy
imagecopy($dest, $src, $start_x, $start_y, 0,0,$width, $height);
// Output and free from memory
header('Content-Type: image/jpeg');
imagejpeg($dest);

imagedestroy($dest);
imagedestroy($src);


No comments: