PHP服務端圖片產生縮圖

來源:互聯網
上載者:User
<?php/* * @author : xiaojiang * @time   : 2013-04-25 *///定義縮圖片尺寸$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 為此檔案。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.