php使用GD创建保持宽高比缩略图的方法

yipeiwu_com5年前PHP代码库

本文实例讲述了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程序设计有所帮助。

相关文章

php操作sqlserver关于时间日期读取的小小见解

上周五,要做一个php 同时对mysql数据库和sqlserver数据库的连接东东 以前一直在用mysql对sqlserver不是很熟悉,于是摸着石头过河。没有别的至少mysql和sql...

PHP中$this和$that指针使用实例

PHP5中定义了一个特殊的方法名“__clone()”方法,是在对象克隆时自动调用的方法,用“__clone()”方法将建立一个与原对象拥有相同属性和方法的对象,如果想在克隆后改变原对象...

PHP经典算法集锦【经典收藏】

本文实例总结了PHP经典算法。分享给大家供大家参考,具体如下: 1、首先来画个菱形玩玩,很多人学C时在书上都画过,咱们用PHP画下,画了一半。 思路:多少行for一次,然后在里面空格和星...

详解WordPress开发中的get_post与get_posts函数使用

get_post() 在一般主题制作时,get_post()函数我们一般很少会用到,但因为后面会讲到get_posts(),所以我们不得不先讲一下这个单数形式。这个函数的主要作用是,将...

PHP使用XMLWriter读写xml文件操作详解

本文实例讲述了PHP使用XMLWriter读写xml文件操作。分享给大家供大家参考,具体如下: 米扑科技旗下的多个产品,需要脚本自动生成sitemap.xml,于是重新温习一遍PHP X...