note 72260 deleted from function.imagejpeg by nlopess
| From: | nlopess@php.net | Date: | Wed, 10 Jan 2007 14:53:49 +0000 |
| Subject: | note 72260 deleted from function.imagejpeg by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-121533@lists.php.net to get a copy of this message | ||
Note Submitter: vindimy.notforspammerz aT gmail
----
A complete function for creating thumbnails (tested). Has an option of returning the thumbnail data
directly to a variable, if you plan to insert stuff into database or use it for some other purposes.
Most code based on createthumb() from http://icant.co.uk/articles/phpthumbnails/
Thanks.
<?php
/*
Function createthumb($name,$filename,$new_w,$new_h)
creates a resized image
variables:
$name Original filename
$filename Filename of the resized image (return raw image data if empty)
$new_w width of resized image
$new_h height of resized image
*/
function createthumb($name, $filename, $new_w, $new_h)
{
if (preg_match("/jpg|jpeg/", strtolower(substr($name, strlen($name) - 3, 3))))
{
$src_img = imagecreatefromjpeg($name);
}
elseif (preg_match("/png/", strtolower(substr($name, strlen($name) - 3, 3))))
{
$src_img = imagecreatefrompng($name);
}
else
{
echo "\nError in createthumb(): can't determine image type (not png or jpeg/jpg for
filename '$name')!\n";
exit();
}
$old_x = imageSX($src_img);
$old_y = imageSY($src_img);
if ($old_x > $old_y)
{
$thumb_w = $new_w;
$thumb_h = $old_y * ($new_h / $old_x);
}
if ($old_x < $old_y)
{
$thumb_w = $old_x * ($new_w / $old_y);
$thumb_h = $new_h;
}
if ($old_x == $old_y)
{
$thumb_w = $new_w;
$thumb_h = $new_h;
}
$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);
if (preg_match("/png/", strtolower(substr($name, strlen($name) - 3, 3))))
{
if (empty($filename))
{
$resimg = imagepng($dst_img);
}
else
{
ob_start();
imagepng($dst_img);
$resimg = ob_get_contents();
ob_end_clean();
}
}
else
{
if (empty($filename))
{
ob_start();
imagejpeg($dst_img);
$resimg = ob_get_contents();
ob_end_clean();
}
else
{
imagejpeg($dst_img,$filename);
}
}
imagedestroy($dst_img);
imagedestroy($src_img);
if (empty($filename))
{
return $resimg;
}
}
?>