这篇文章主要介绍了PHP生成缩略图实例讲解,文章列举了实例代码,有正好需要的同学可以借鉴下
封装的方法函数:
<?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="RDovUEhQL3Rlc3QvZGVtby5qcGc=";
//缩略图路径
$thumbSrc="RDovUEhQL3Rlc3QvdGh1bWIuanBn";
createThumbImg($path,100,100,$thumbSrc);
?>
到此这篇关于PHP生成缩略图实例讲解的文章就介绍到这了,更多相关PHP生成缩略图内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
沃梦达教程
本文标题为:PHP生成缩略图实例讲解
猜你喜欢
- 用nohup命令实现PHP的多进程 2023-09-02
- php微信公众号开发之秒杀 2022-11-23
- Laravel balde模板文件中判断数据为空方法 2023-08-30
- PHP仿tp实现mvc框架基本设计思路与实现方法分析 2022-10-18
- windows下9款一键快速搭建PHP本地运行环境的好工具(含php7.0环境) 2023-09-02
- laravel实现按月或天或小时统计mysql数据的方法 2023-02-22
- laravel通用化的CURD的实现 2023-03-17
- PHP简单实现二维数组的矩阵转置操作示例 2022-10-02
- PHP中PDO事务处理操作示例 2022-10-15
- PHP实现微信支付(jsapi支付)流程步骤详解 2022-10-09