1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
/**
* Scale an image according to input canvas dimensions.
* No cropping will occur, the scaled image is "centered" to canvas.
*/
function imageToCanvas ($_image, $_canvasWidth, $_canvasHeight)
{
if (is_string($_image)) {
if (is_file($_image)) {
$_image = imagecreatefromjpeg($_image);
} else {
return "Incorrect imagepath >> No file here " . $_image;
}
}
$width = imagesx($_image);
$height = imagesy($_image);
$image_aspect_ratio = $width / $height;
$canvas_aspect_ratio = $_canvasWidth / $_canvasHeight;
// scale by height
if ($image_aspect_ratio < $canvas_aspect_ratio) {
$new_height = $_canvasHeight;
$new_width = ($new_height/$height) * $width;
}
// scale by width
else {
$new_width = $_canvasWidth;
$new_height = ($new_width/$width) * $height;
}
# offset values (ie. center the resized image to canvas)
$xoffset = ($_canvasWidth - $new_width) / 2;
$yoffset = ($_canvasHeight - $new_height) / 2;
$image_resized = imagecreatetruecolor($_canvasWidth, $_canvasHeight);
# fill colour
$white = imagecolorallocate($image_resized, 255, 255, 255);
imagefill($image_resized, 0, 0, $white);
imagecopyresampled($image_resized, $_image, $xoffset, $yoffset, 0, 0, $new_width, $new_height, $width, $height);
imagedestroy($_image);
return $image_resized;
}
Refactorings
No refactoring yet !
Chris Dean
August 14, 2008, August 14, 2008 07:00, permalink
I don't see any real issues with the way this works, though it all applies to GD lib - unless you're doing a check to see if GD lib's available elsewhere maybe you'd want to include something like that?
Juha Hollanti
August 14, 2008, August 14, 2008 08:11, permalink
Checking for GD lib might actually be prudent. I once lost hours trying to get something like a picture upload working on a new server. For some reason nothing gave out any error messages.
bruce
September 29, 2008, September 29, 2008 20:20, permalink
#1 problem I can see is it only accepts jpegs
The built in image functions found in PHP manage to boggle my mind to a point where i can no longer understand anything of what's going on. I'll just end up messing around long enough to get things right.
For this reason i'm always trying to write up functions (which often end up horribly wrong) that would obfuscate all the mind boggling soup out of my sight.
Anything to make the following more bearable to live with is very, very welcome. Thanks.