PHP生成缩略图实例讲解

2022-04-15 0 626

封装的方法函数:

<?php
	/**
  * 生成缩略图
  * $imgSrc     图片源路径
  * $thumbWidth   缩略图宽度
  * $thumbHeight  缩略图高度
  * $thumbSrc    缩略图路径
  * $isCut     是否剪切图片
  */
  function createThumbImg($imgSrc, $thumbWidth, $thumbHeight, $thumbSrc, $isCut = false) {
    //1.获取图片的类型
    $type = substr(strrchr($imgSrc, "."), 1);
    //2.初始化图象
    if ($type == "jpg" || $type == "jpeg") {
			//创建一块画布,并从JPEG文件或URL地址载入一副图像
      $sourceImg = imagecreatefromjpeg($imgSrc);
    }elseif ($type == "gif") {
			//创建一块画布,并从GIF文件或URL地址载入一副图像
      $sourceImg = imagecreatefromgif($imgSrc);
    }elseif ($type == "png") {
			//创建一块画布,并从PNG文件或URL地址载入一副图像
      $sourceImg = imagecreatefrompng($imgSrc);
    }
		elseif ($type == "wbmp") {
			//创建一块画布,并从WBMP文件或URL地址载入一副图像
      $sourceImg = imagecreatefromwbmp($imgSrc);
    }
		//取得图像宽度
    $width = imagesx($sourceImg);
		//取得图像高度
    $height = imagesy($sourceImg);
 
    //3.生成图象
    //缩略图的图象比例
    $scale = ($thumbWidth) / ($thumbHeight);
    //源图片的图象比例
    $ratio = ($width) / ($height);
    if (($isCut) == 1) {
			//高度优先
      if ($ratio >= $scale) {        
				//创建真彩图像资源(imagecreatetruecolor()函数使用GDLibrary创建新的真彩色图像)
        $newimg = imagecreatetruecolor($thumbWidth, $thumbHeight);
				//图像处理
        imagecopyresampled($newimg, $sourceImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, (($height) * $scale), $height);
        //以JPEG格式将图像输出到浏览器或文件
				ImageJpeg($newimg, $thumbSrc);
      }
			 //宽度优先
      if ($ratio < $scale) {       
        $newimg = imagecreatetruecolor($thumbWidth, $thumbHeight);
        imagecopyresampled($newimg, $sourceImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, (($width) / $scale));
        ImageJpeg($newimg, $thumbSrc);
      }
    } else {
      if ($ratio >= $scale) {
        $newimg = imagecreatetruecolor($thumbWidth, ($thumbWidth) / $ratio);
        imagecopyresampled($newimg, $sourceImg, 0, 0, 0, 0, $thumbWidth, ($thumbWidth) / $ratio, $width, $height);
        ImageJpeg($newimg, $thumbSrc);
      }
      if ($ratio < $scale) {
        $newimg = imagecreatetruecolor(($thumbHeight) * $ratio, $thumbHeight);
        imagecopyresampled($newimg, $sourceImg, 0, 0, 0, 0, ($thumbHeight) * $ratio, $thumbHeight, $width, $height);
        ImageJpeg($newimg, $thumbSrc);
      }
    }
		//销毁图像
    ImageDestroy($sourceImg);
  }
?>

调用示例:

<?php
	//图片源路径
	$imgSrc="D:/PHP/test/demo.jpg";
	//缩略图路径
	$thumbSrc="D:/PHP/test/thumb.jpg";
	createThumbImg($path,100,100,$thumbSrc);
?>

到此这篇关于PHP生成缩略图实例讲解的文章就介绍到这了,更多相关PHP生成缩略图内容请搜索NICE源码以前的文章或继续浏览下面的相关文章希望大家以后多多支持NICE源码!

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 PHP编程 PHP生成缩略图实例讲解 https://www.niceym.com/17523.html