宜昌本地软件开发与弱电工程服务商
项目咨询 · 快速响应
您当前的位置: > 博客2 > PHP教程

[PHP]PHP图片缩放函数:实现等比例不失真缩放

2016-10-13 00:16:48 点击量:32 标签: 收藏本文

参数说明:
$im 图片对象,应用函数之前,你需要用imagecreatefromjpeg()读取图片对象,如果PHP环境支持PNG,GIF,也可使用imagecreatefromgif(),imagecreatefrompng();
$maxwidth 定义生成图片的最大宽度(单位:像素)
$maxheight 生成图片的最大高度(单位:像素)
$name 生成的图片名
$filetype 最终生成的图片类型(.jpg/.png/.gif)

特别说明:
GD库1.6.2版以前支持GIF格式,但因GIF格式使用LZW演算法牵涉专利权,因此在GD1.6.2版之后不支持GIF的格式。如果你是 WINDOWS的环境,你只要进入PHP.INI文件找到extension=php_gd2.dll,将#去除,重启APACHE即可,如果你是 Linux环境,又想支持GIF,PNG,JPEG,你需要去下载libpng,zlib,以及freetype字体并安装。

  1. function resizeImage($im,$maxwidth,$maxheight,$name,$filetype) 
  2.     $pic_width = imagesx($im); 
  3.     $pic_height = imagesy($im); 
  4.     if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) 
  5.     { 
  6.         if($maxwidth && $pic_width>$maxwidth) 
  7.         { 
  8.             $widthratio = $maxwidth/$pic_width; 
  9.             $resizewidth_tag = true
  10.         } 
  11.         if($maxheight && $pic_height>$maxheight) 
  12.         { 
  13.             $heightratio = $maxheight/$pic_height; 
  14.             $resizeheight_tag = true
  15.         } 
  16.         if($resizewidth_tag && $resizeheight_tag) 
  17.         { 
  18.             if($widthratio<$heightratio) 
  19.                 $ratio = $widthratio; 
  20.             else 
  21.                 $ratio = $heightratio; 
  22.         } 
  23.         if($resizewidth_tag && !$resizeheight_tag) 
  24.             $ratio = $widthratio; 
  25.         if($resizeheight_tag && !$resizewidth_tag) 
  26.             $ratio = $heightratio; 
  27.         $newwidth = $pic_width * $ratio; 
  28.         $newheight = $pic_height * $ratio; 
  29.         if(function_exists("imagecopyresampled")) 
  30.         { 
  31.             $newim = imagecreatetruecolor($newwidth,$newheight); 
  32.            imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height); 
  33.         } 
  34.         else 
  35.         { 
  36.             $newim = imagecreate($newwidth,$newheight); 
  37.            imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height); 
  38.         } 
  39.         $name = $name.$filetype; 
  40.         imagejpeg($newim,$name); 
  41.         imagedestroy($newim); 
  42.     } 
  43.     else 
  44.     { 
  45.         $name = $name.$filetype; 
  46.         imagejpeg($im,$name); 
  47.     }          

 

ABOUT US
宜昌农人网络科技有限公司

我们是一家提供综合软件外包与弱电工程服务的技术公司。

业务涵盖定制软件、管理系统、网站、小程序、APP、系统集成、网络布线、监控安防、门禁、机房建设及长期技术维护。

公司地址:湖北省宜昌市伍家岗区东站二路6号三峡(宜昌)大数据产业园海洋馆二楼A203室