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

 2025-01-15  阅读 361  评论 8  点赞 397

摘要:本文实例讲述了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 t

本文实例讲述了php使用gd创建保持宽高比缩略图的方法。分享给大家供大家参考。具体如下:

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程序设计有所帮助。


标签:phpphp教程

评论列表:

  •   weihang666
     发布于 3天前回复该评论
  • 写的很不错,学到了!
  •   rick.li
     发布于 3天前回复该评论
  • 写的很不错,学到了!
  •   henbucuo
     发布于 2天前回复该评论
  • 写的很不错,学到了!
显示更多评论

发表评论:

管理员

承接各种程序开发,外贸网站代运营,外贸网站建设等项目
  • 内容2460
  • 积分67666
  • 金币86666

Copyright © 2024 LS'Blog-保定PHP程序员老宋个人博客 Inc. 保留所有权利。 Powered by LS'blog 3.0.3

页面耗时0.0389秒, 内存占用1.95 MB, 访问数据库32次

冀ICP备19034377号