生成无失真不变形图片类

 <?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("输入的图片格式错误");
 }
}
?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值