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

yipeiwu_com4年前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生成器功能与用法。分享给大家供大家参考,具体如下: 1. 官方说明:生成器提供了一种更容易的方法来实现简单的对象迭代,相比较定义类实现 Iterator 接口的方式,...

apache和php之间协同工作的配置经验分享

php在当今一个不陌生的网络技术名词,想到网站或者web可能大多数开发者都会想到php,一个既免费又开源,既容易又实用等一些好处才拥有了世界上很多IT技术人员的青睐,我是一名JAVA开发...

php引用计数器进行垃圾收集机制介绍

PHP 有一个非常简单的垃圾收集器,它实际上将对不再位于内存范围(scope)中的对象进行垃圾收集。垃圾收集的内部方式是使用一个引用计数器,因此当计数器达到 0 时(意味着对该对象的引用...

浅谈php和js中json的编码和解码

php中 1)编码 $jsonStr = json_encode($array) 2)解码 $arr = json_decode($jsonStr) <?php echo...

php短信接口代码

本文实例为大家分享了几个常用的php短信接口代码,供大家参考,具体内容如下 1. 短信调用class     <?php /...