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设计模式 php实现工厂模式(factory)

学习php设计模式 php实现工厂模式(factory)

一、意图 定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method使用一个类的实例化延迟到其子类【GOF95】 二、工厂模式结构图 三、工厂模式中主要角色...

PHP实现通过get方式识别用户发送邮件的方法

本文实例讲述了PHP实现通过get方式识别用户发送邮件的方法。分享给大家供大家参考。具体如下: send_email.php如下: <?php $conn=mysq...

PHP 进程锁定问题分析研究

1. 区分读锁定 和 写 锁定。 如果每次都使用 写锁定,那么连多个进程读取一个文件也要排队,这样的效率肯定不行。 2. 区分 阻塞 与 非 阻塞模式。 一般来说,如果一个进程在写一个文...

浅谈php://filter的妙用

浅谈php://filter的妙用

php://filter是PHP中独有的协议,利用这个协议可以创造很多“妙用”,本文说几个有意思的点,剩下的大家自己下去体会。本来本文的思路我上半年就准备拿来做XDCTF2016的题目的...

Zend的AutoLoad机制介绍

代码示例 复制代码 代码如下: set_include_path(USVN_LIB_DIR . PATH_SEPARATOR . get_include_path()); require...