基于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获取今日开始时间和结束时间的方法

话不多说,请看代码:  $begintime=date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d'),date('Y')))...

php清空(删除)指定目录下的文件,不删除目录文件夹的实现代码

web 开发中我们可能会碰到需要将某个目录下的所有文件清空,但不删除这个目录下的子目录(当然也不会删除被删除的根目录)的情况。那么对于这种只删除文件而不删除目录的方法,你是如何处理的呢?...

解析PHP中的正则表达式以及模式匹配

PHP中对于正则处理文本提供了两种方式,一种是PCRE方式(PCRE库是一个实现了与perl 5在语法和语义上略有差异(详见下文)的正则表达式模式匹配功能的函数集. 当前的实现对应于pe...

PHP7中I/O模型内核剖析详解

PHP7中I/O模型内核剖析详解

1.同步:我客户端(C端调用者)一个功能,该功能没有结束前,我死等结果。 2.异步:我(c端调用者)调用一个功能,不知道该功能结果,该功能有结果后通知我,即回调通知 3.阻塞:就是调用我...

php实现对文件压缩简单的方法

压缩一个文件 我们将一个文件生成一个压缩包。 <?php $path = "c:/wamp/www/log.txt"; $filename = "test.zip"...