• 技术文章 >后端开发 >php教程

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

    2016-05-17 09:00:02原创418
    复制代码 代码如下:

    //定义缩略图片尺寸
    $picSize = array(
    '100_100'=> 1,
    '200_100'=> 1
    );
    $imagePath = "../image/";
    function parseUrl($url){
    preg_match("/(?P[\w\d]+)_w(?P\d+)_h(?P\d+)\.(?P\w+)/",$url,$match);
    return $match;
    }
    $urlArr = explode("//m.sbmmt.com/m/",$_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'].'//m.sbmmt.com/m/'.$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']."//m.sbmmt.com/m/".$imgName, $_newImg);
    header("Content-type:image/jpeg; charset=utf-8");
    imagejpeg($new_img);
    ?>

    使用时候绑定apache conf 的 documentError 404 的handler 为此文件。。
    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    上一篇:解析左右值无限分类的实现算法_php技巧 下一篇:解析如何用php screw加密php源代码_php技巧
    VIP课程(WEB全栈开发)

    相关文章推荐

    • 【腾讯云】年中优惠,「专享618元」优惠券!• PHP面试之常见基础算法(附代码示例)• 微信摇一摇周边 红包,摇周边红包_PHP教程• PHP错误Warning:mysql_query()解决方法,warningmysql_query_PHP教程• 学习小笔记---大话PHP设计模式_PHP教程• php设计模式入门-单例模式_PHP教程
    1/1

    PHP中文网