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

yipeiwu_com5年前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聊天室简单实现方法详解

本文实例讲述了PHP聊天室简单实现方法。分享给大家供大家参考,具体如下: 用户 => 客服 (先把信息入库,然后通过ob+长连接不断从数据库查询数据发送给客服) 客服 =>...

PHP 模拟登陆功能实例详解

PHP 模拟登陆功能实例详解

本文实例讲述了PHP 模拟登陆功能。分享给大家供大家参考,具体如下: 说明:该模拟登陆实例仅适用于没有验证码的模拟登陆实例 该程序基本功能是,模拟登陆高校图书馆网站,并获取读者信息和借书...

Http 1.1 Etag 与 Last-Modified提高php效率

Http 1.1 Etag 与 Last-Modified提高php效率

在 Blog 盛行的今天,一些 Web 应用需要解析大量的 RSS Feed .如何提高效率是个非常重要的问题.在 MagpieRSS 的 Features 中列举了这样的一条: HT...

PHP获取HTTP body内容的方法

有时候我们获取数据时需要根据Header中的格式来解析,比如上传一个json而不是一个文本。这里用到了 php输入|输出流 的概念。 PHP 提供了一些杂项输入/输出(IO)流,允许访问...

php SQL防注入代码集合

SQL防注入代码一复制代码 代码如下: <?php /** * 防sql注入 * @author: zhuyubing@gmail.com * */ /** * reject sq...