<?php
/*
*本类实现了将图像生成无失真图像缩略图的功能,如果比例失调的话,将会加白边。
*作者:hyc
*/
class PhotoZoom
{
//缩略图象宽,长。
private $newWidth,$newHeight,$type,$newFilePath;
//缩略图象默认初始化大小,及生成类型
public function __construct($maxWidth=400,$maxHeight=400,$newFilePath,$type="jpg")
{
$this->setSize($maxWidth,$maxHeight);
$this->setFilePath($newFilePath);
$this->type=$type;
}
//改变缩放图象的默认大小
public function setSize($newWidth,$newHeight)
{
$this->newWidth=$newWidth;
$this->newHeight=$newHeight;
}
//设置生成图片的类型
public function setFilePath($newFilePath)
{
$this->newFilePath=$newFilePath;
}
//生成缩略图片
//参数:$ImgFile 图片信息数组,包括名称:name 类型:type 大小:size 文件的完整名称tmp_nam
//参数:$newFileName 新文件的文件名
public function makePhotoZoom($ImgFile,$newFileName)
{
if(($ImgFile['type'] == "image/jpg") || ($ImgFile['type'] =="image/pjpeg"))
{
$im = imagecreatefromjpeg($ImgFile['tmp_name']);
}
else if($ImgFile['type'] == "image/x-png")
{
$im = imagecreatefrompng($ImgFile['tmp_name']);
}
else if($ImgFile['type'] == "image/gif")//image/pjpeg
{
$im = imagecreatefromgif($ImgFile['tmp_name']);
}
else
{
die('您指定的不是可用的图片类型');
}
$newim = imagecreatetruecolor($this->newWidth, $this->newHeight);
$back = imagecolorallocate($newim, 255, 255, 255);
imagefilledrectangle($newim, 0, 0, $this->newWidth, $this->newHeight, $back);
$imgWidth = imagesx($im);//获得图片的宽
$imgHeight = imagesY($im);//获得图片的高
$imgX = 0;//设置新图片在画布上的绘画起始X坐标
$imgY = 0;//设置新图片在画布上的绘画起始Y坐标
$widhtScale = $this->newWidth/$imgWidth;//获得原图片和新图片的宽的比例
$heightScale = $this->newHeight/$imgHeight;//获得原图片和新图片的高的比例
$photoScale = $imgWidth/$imgHeight;
$canvasScale = $this->newWidth/$this->newHeight;
$newImgWidth = $this->newWidth;
$newImgHeight = $this->newHeight;
if(abs($canvasScale-$photoScale) > 0.01)
{
if($widhtScale < $heightScale)//这个算法是实现图像不变形的重点
{
$newImgHeight = intval($widhtScale*$imgHeight);
$imgY = intval(($this->newHeight-$newImgHeight)/2);
}
else
{
$newImgWidth = intval($heightScale*$imgWidth);
$imgX = intval(($this->newWidth-$newImgWidth)/2);
}
}
imagecopyresampled($newim, $im, $imgX, $imgY, 0, 0, $newImgWidth, $newImgHeight, $imgWidth, $imgHeight);
$this->makeImage($newim,$newFileName);
ImageDestroy ($im);
ImageDestroy ($newim);
return true;
}
//类型图片源
private function makeImage($newim,$newFileName)
{
if ($this->type=="jpg")
{
imagejpeg($newim,$this->newFilePath . $newFileName .'.'. $this->type);
return ;
}
if ($this->type=="gif")
{
imagegif($newim,$this->newFilePath . $newFileName .'.'. $this->type);
return ;
}
if ($this->type=="png")
{
imagepng($newim,$newFilePath . $newFileName .'.'. $this->type);
return ;
}
die("输入的图片格式错误");
}
}
?>
生成无失真不变形图片类
最新推荐文章于 2024-09-13 16:27:15 发布