温馨提示×

温馨提示×

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

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

如何在PHP中使用GD库生成图片缩略图

发布时间:2021-02-05 16:13:29 来源:亿速云 阅读:154 作者:Leah 栏目:开发技术

本篇文章给大家分享的是有关如何在PHP中使用GD库生成图片缩略图,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

具体如下:

<?php
/**
 * 生成缩略图函数(支持图片格式:gif、jpeg、png和bmp)
 * @author ruxing.li
 * @param string $src   源图片路径
 * @param int  $width  缩略图宽度(只指定高度时进行等比缩放)
 * @param int  $width  缩略图高度(只指定宽度时进行等比缩放)
 * @param string $filename 保存路径(不指定时直接输出到浏览器)
 */
function mkThumbnail($src, $width = null, $height = null, $filename = null) {
  if (!isset($width) && !isset($height))
    return false;
  if (isset($width) && $width <= 0)
    return false;
  if (isset($height) && $height <= 0)
    return false;
  $size = getimagesize($src);
  if (!$size)
    return false;
  list($src_w, $src_h, $src_type) = $size;
  $src_mime = $size['mime'];
  switch($src_type) {
    case 1 :
      $img_type = 'gif';
      break;
    case 2 :
      $img_type = 'jpeg';
      break;
    case 3 :
      $img_type = 'png';
      break;
    case 15 :
      $img_type = 'wbmp';
      break;
    default :
      return false;
  }
  if (!isset($width))
    $width = $src_w * ($height / $src_h);
  if (!isset($height))
    $height = $src_h * ($width / $src_w);
  $imagecreatefunc = 'imagecreatefrom' . $img_type;
  $src_img = $imagecreatefunc($src);
  $dest_img = imagecreatetruecolor($width, $height);
  imagecopyresampled($dest_img, $src_img, 0, 0, 0, 0, $width, $height, $src_w, $src_h);
  $imagefunc = 'image' . $img_type;
  if ($filename) {
    $imagefunc($dest_img, $filename);
  } else {
    header('Content-Type: ' . $src_mime);
    $imagefunc($dest_img);
  }
  imagedestroy($src_img);
  imagedestroy($dest_img);
  return true;
}
$result = mkThumbnail('./IMG_3324.JPG', 147, 147);

以上就是如何在PHP中使用GD库生成图片缩略图,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

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

php
AI