如何使用PHP实现服务端图片生成缩略图

发布时间:2021-10-08 16:14:17 作者:小新
来源:亿速云 阅读:121

这篇文章主要介绍如何使用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实现服务端图片生成缩略图”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. PHP 图片处理,生成缩略图、圆形图片
  2. js使用canvas实现生成图片缩略图

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php

上一篇:asp.net中TextBox只能输入数字的最简洁的方法有哪些

下一篇:如何理解shell编程中的BASH

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》