基于PHP服务端图片生成缩略图的方法详解

yipeiwu_com6年前PHP代码库
复制代码 代码如下:

<?php
//定义缩略图片尺寸
$picSize = array(
              '100_100'=> 1,
              '200_100'=> 1
           );
$imagePath = "../image/";
function parseUrl($url){
   preg_match("/(?P<name>[\w\d]+)_w(?P<width>\d+)_h(?P<height>\d+)\.(?P<ext>\w+)/",$url,$match);
   return $match;
}
$urlArr = explode("/",$_SERVER['REQUEST_URI']);
$imgName = $urlArr[count($urlArr)-1];
$picInfo = parseUrl($imgName);
//错误尺寸
if(empty($picInfo['width']) || empty($picInfo['height']) ||
!array_key_exists($picInfo['width'].'_'.$picInfo['height'],$picSize)) die('不存在该尺寸图片');
$originalPic = $imagePath.$picInfo['name'].'/'.$picInfo['name'].'.'.$picInfo['ext'];
//原始图不存在
if(!file_exists($originalPic)) die("图片不存在!");
/**
 *等比例压缩图片
 */
switch($picInfo['ext']){
   case 'jpg':
      $orgImg = ImageCreateFromJpeg($originalPic);
      break;
   default:
      break;
}
$owidth  =  ImageSX($orgImg); //原始尺寸
$oheight =  ImageSY($orgImg);
$tW = $picInfo['width'];
$tH = $picInfo['height'];
//获取缩略图尺寸
if($owidth/$oheight > $tW/$tH){
    $tH = intval($tW * $oheight/$owidth);
}else{
     $tW = intval($tH * $owidth/$oheight);
}
//生成背景图
$new_img = ImageCreateTrueColor($picInfo['width'], $picInfo['height']);
$bgColor = imagecolorallocate($new_img,255,255,255);
if (!@imagefilledrectangle($new_img, 0, 0, $picInfo['width']-1, $picInfo['height']-1, $bgColor)) {
    echo "无法创建背景图";  //@todo记录日志
    exit(0);
}
if (!@imagecopyresampled($new_img, $orgImg, ($picInfo['width']-$tW)/2, ($picInfo['height']-$tH)/2, 0, 0, $tW, $tH, $owidth, $oheight)) {
    echo "生成图片失败";
    exit(0);
}
//生成图片
ob_start();
imagejpeg($new_img);
$_newImg = ob_get_contents();
ob_end_clean();
file_put_contents($imagePath.$picInfo['name']."/".$imgName, $_newImg);
header("Content-type:image/jpeg; charset=utf-8");
imagejpeg($new_img);
?>

使用时候绑定apache conf 的 documentError 404 的handler 为此文件。。

相关文章

PHP对象实例化单例方法

PHP实例化对象单例的方法: 三私一公:2个私有方法,1个私有属性,1个公共方法   private function __construct(){} //不可以继承构造方法   p...

PHP代码维护,重构变困难的4种原因分析

本文分析讲述了PHP代码维护,重构变困难的4种原因。分享给大家供大家参考,具体如下: 代码维护,重构是件很令人不爽的一件事。以下几种情况,会让代码维护和重构变得很困难。 1. 项目开始时...

php命名空间学习详解

1、什么是命名空间?命名空间是一种特殊的作用域,它包含处于该作用域下的标识符,同时它本身也是一种标识符。可以把命名空间与操作系统的目录对应起来。一个命名空间相当于一个目录,命名空间里的类...

php实现把数组按指定的个数分隔

复制代码 代码如下:/** *  * 把数组按指定的个数分隔 * @param array $array 要分割的数组 * @param int...

php中引用&的用法分析【变量引用,函数引用,对象引用】

php中引用&的用法分析【变量引用,函数引用,对象引用】

本文实例分析了php中引用&的用法。分享给大家供大家参考,具体如下: php的引用(就是在变量或者函数、对象等前面加上&符号) //最重要就是 删除引用的变量 ,只是引用的变量访问不了,...