php使用GD创建保持宽高比缩略图的方法
程序员文章站
2022-06-18 16:29:36
本文实例讲述了php使用gd创建保持宽高比缩略图的方法。分享给大家供大家参考。具体如下:
/**
* create a thumbnail image from...
本文实例讲述了php使用gd创建保持宽高比缩略图的方法。分享给大家供大家参考。具体如下:
/** * create a thumbnail image from $inputfilename no taller or wider than * $maxsize. returns the new image resource or false on error. * author: mthorn.net */ function thumbnail($inputfilename, $maxsize = 100) { $info = getimagesize($inputfilename); $type = isset($info['type']) ? $info['type'] : $info[2]; // check support of file type if ( !(imagetypes() & $type) ) { // server does not support file type return false; } $width = isset($info['width']) ? $info['width'] : $info[0]; $height = isset($info['height']) ? $info['height'] : $info[1]; // calculate aspect ratio $wratio = $maxsize / $width; $hratio = $maxsize / $height; // using imagecreatefromstring will automatically detect the file type $sourceimage = imagecreatefromstring(file_get_contents($inputfilename)); // calculate a proportional width and height no larger than the max size. if ( ($width <= $maxsize) && ($height <= $maxsize) ) { // input is smaller than thumbnail, do nothing return $sourceimage; } elseif ( ($wratio * $height) < $maxsize ) { // image is horizontal $theight = ceil($wratio * $height); $twidth = $maxsize; } else { // image is vertical $twidth = ceil($hratio * $width); $theight = $maxsize; } $thumb = imagecreatetruecolor($twidth, $theight); if ( $sourceimage === false ) { // could not load image return false; } // copy resampled makes a smooth thumbnail imagecopyresampled($thumb,$sourceimage,0,0,0,0,$twidth,$theight,$width,$height); imagedestroy($sourceimage); return $thumb; } /** * save the image to a file. type is determined from the extension. * $quality is only used for jpegs. * author: mthorn.net */ function imagetofile($im, $filename, $quality = 80) { if ( !$im || file_exists($filename) ) { return false; } $ext = strtolower(substr($filename, strrpos($filename, '.'))); switch ( $ext ) { case '.gif': imagegif($im, $filename); break; case '.jpg': case '.jpeg': imagejpeg($im, $filename, $quality); break; case '.png': imagepng($im, $filename); break; case '.bmp': imagewbmp($im, $filename); break; default: return false; } return true; } $im = thumbnail('temp.jpg', 100); imagetofile($im, 'temp-thumbnail.jpg');
希望本文所述对大家的php程序设计有所帮助。