---
title: "使用PHP实现生成固定大小图片缩略图功能（智能裁剪，图片不失真）"
author: "mmdev"
date: "2011-12-30T15:12:00Z"
tags: []
slug: "php"
draft: false
lastmod: "2012-03-08T22:49:55Z"
id: 1447156
url: "https://mmdev.iteye.com/blog/1447156"
---

&lt;?php  
//图像处理类  
class Image {  
private $file;//图片地址  
private $width;//图片长度  
private $height;//图片长度  
private $type;//图片类型  
private $img;//原图的资源句柄  
private $new;//新图的资源句柄

//构造方法，初始化  
public function \_\_construct($\_file) {  
$this-&gt;file = $\_SERVER\["DOCUMENT\_ROOT"].$\_file;  
list($this-&gt;width, $this-&gt;height, $this-&gt;type) = getimagesize($this-&gt;file);  
$this-&gt;img = $this-&gt;getFromImg($this-&gt;file, $this-&gt;type);  
}

//缩略图(固定长高容器，图像等比例，扩容填充，裁剪)\[固定了大小，不失真，不变形]  
public function thumb($new\_width = 0,$new\_height = 0) {

if (empty($new\_width) && empty($new\_height)) {  
$new\_width = $this-&gt;width;  
$new\_height = $this-&gt;height;  
}

if (!is\_numeric($new\_width) || !is\_numeric($new\_height)) {  
$new\_width = $this-&gt;width;  
$new\_height = $this-&gt;height;  
}

//创建一个容器  
$\_n\_w = $new\_width;  
$\_n\_h = $new\_height;

//创建裁剪点  
$\_cut\_width = 0;  
$\_cut\_height = 0;

if ($this-&gt;width &lt; $this-&gt;height) {  
$new\_width = ($new\_height / $this-&gt;height) * $this-&gt;width;  
} else {  
$new\_height = ($new\_width / $this-&gt;width) * $this-&gt;height;  
}

if ($new\_width &lt; $\_n\_w) { //如果新高度小于新容器高度  
$r = $\_n\_w / $new\_width; //按长度求出等比例因子  
$new\_width \*= $r; //扩展填充后的长度  
$new\_height \*= $r; //扩展填充后的高度  
$\_cut\_height = ($new\_height - $\_n\_h) / 2; //求出裁剪点的高度  
}

if ($new\_height &lt; $\_n\_h) { //如果新高度小于容器高度  
$r = $\_n\_h / $new\_height; //按高度求出等比例因子  
$new\_width \*= $r; //扩展填充后的长度  
$new\_height \*= $r; //扩展填充后的高度  
$\_cut\_width = ($new\_width - $\_n\_w) / 2; //求出裁剪点的长度  
}

$this-&gt;new = imagecreatetruecolor($\_n\_w,$\_n\_h);  
imagecopyresampled($this-&gt;new,$this-&gt;img,0,0,$\_cut\_width,$\_cut\_height,$new\_width,$new\_height,$this-&gt;width,$this-&gt;height);  
}

//加载图片，各种类型，返回图片的资源句柄  
private function getFromImg($\_file, $\_type) {  
switch ($\_type) {  
case 1 :  
$img = imagecreatefromgif($\_file);  
break;  
case 2 :  
$img = imagecreatefromjpeg($\_file);  
break;  
case 3 :  
$img = imagecreatefrompng($\_file);  
break;  
default:  
Tool::alertBack('警告：此图片类型本系统不支持！');  
}  
return $img;  
}

//图像输出  
public function out() {  
imagepng($this-&gt;new,$this-&gt;file);  
imagedestroy($this-&gt;img);  
imagedestroy($this-&gt;new);  
}  
}

?&gt;

使用方法：

$\_path = 'D:/test1.png';

$\_img = new Image($\_path);//$\_path为图片文件的路径  
$\_img-&gt;thumb(150, 100);  
$\_img-&gt;out();