源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2021-01-21 23:00 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:基于PHP服务端图片生成缩略图的方法详解
[u]复制代码[/u] 代码如下:
<?php [b]//定义缩略图片尺寸 [/b]$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); [b]//错误尺寸 [/b]if(empty($picInfo['width']) || empty($picInfo['height']) || !array_key_exists($picInfo['width'].'_'.$picInfo['height'],$picSize)) die('不存在该尺寸图片'); $originalPic = $imagePath.$picInfo['name'].'/'.$picInfo['name'].'.'.$picInfo['ext']; [b]//原始图不存在 [/b]if(!file_exists($originalPic)) die("图片不存在!"); /**  *[b]等比例压缩图片 [/b] */ switch($picInfo['ext']){    case 'jpg':       $orgImg = ImageCreateFromJpeg($originalPic);       break;    default:       break; } $owidth  =  ImageSX($orgImg);[b]//原始尺寸 [/b]$oheight =  ImageSY($orgImg); $tW = $picInfo['width']; $tH = $picInfo['height']; [b]//获取缩略图尺寸 [/b]if($owidth/$oheight > $tW/$tH){     $tH = intval($tW * $oheight/$owidth); }else{      $tW = intval($tH * $owidth/$oheight); } [b]//生成背景图 [/b]$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); } [b]//生成图片 [/b]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 为此文件。。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部