Home >Backend Development >PHP Tutorial >PHP generates the same proportion of thumbnail implementation program_PHP tutorial
Generating thumbnails in PHP is commonly used in program development. Below I have found a few good implementation programs for PHP to generate thumbnails. Friends in need can use them. I personally tested them and it is absolutely easy to use.
Creating image thumbnails takes a lot of time, this code will help to understand the logic of thumbnails.
The code is as follows | Copy code | ||||
/********************** *@filename - path to the image *@tmpname - temporary path to thumbnail *@xmax - max width *@ymax - max height */ function resize_image($filename, $tmpname, $xmax, $ymax) { $ext = explode(".", $filename); $ext = $ext[count($ext)-1]; if($ext == "jpg" || $ext == "jpeg") $im = imagecreatefromjpeg($tmpname); elseif($ext == "png") $im = imagecreatefrompng($tmpname); elseif($ext == "gif") $im = imagecreatefromgif($tmpname); $x = imagesx($im); $y = imagesy($im); if($x <= $xmax && $y <= $ymax) return $im;<🎜> <🎜> if($x >= $y) { $newx = $xmax; $newy = $newx * $y / $x; } else { $newy = $ymax; $newx = $x / $y * $newy; } $im2 = imagecreatetruecolor($newx, $newy); Imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y); Return $im2; } |
Example 2
The code is as follows
|
Copy code | ||||
//It is a true color image
if (function_exists("imagecreatetruecolor"))
{
switch($orig_type)
{
//The image obtained from the given gif file name
Case 1 : $thumb_type = ".gif"; $_creatImage = "imagegif"; $_function = "imagecreatefromgif";
break;
//The image obtained from the given jpeg, jpg file name
Case 2 : $thumb_type = ".jpg"; $_creatImage = "imagejpeg"; $_function = "imagecreatefromjpeg";
break;
//The image obtained from the given png file name
Case 3 : $thumb_type = ".png"; $_creatImage = "imagepng"; $_function = "imagecreatefrompng";
break;
}
}
//If the image is available from the given file name
if(function_exists($_function))
{
$orig_image = $_function($img); //The image obtained from the given $img file name
}
if (($orig_x / $orig_y) >= (4 / 3)) //If width/height >= 4/3
{
$y = round($orig_y / ($orig_x / $w)); //Round floating point numbers
$x = $w;
}
else //i.e. height/width >= 4/3
{
$x = round($orig_x / ($orig_y / $h));
$y = $h;
}
$sm_image = imagecreatetruecolor($x, $y); //Create a true color image
//Resample copy part of the image and resize
Imagecopyresampled($sm_image, $orig_image, 0, 0, 0, 0, $x, $y, $orig_x, $orig_y);
//imageJPEG($sm_image, '', 80); //Output the image in the browser
$tnpath = $path."/"."s_".date('YmdHis').$thumb_type; //Thumbnail path
$thumbnail = @$_creatImage($sm_image, $tnpath, 80); //Generate image, return true (or 1) successfully
imagedestroy ($sm_image); //Destroy image
if($thumbnail==true)
{
return $tnpath;
}
}