这篇文章给大家分享的是用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="D:/PHP/test/demo.jpg"; //缩略图路径 $thumbSrc="D:/PHP/test/thumb.jpg"; createThumbImg($path,100,100,$thumbSrc); ?>
以上就是用PHP实现生成缩略图的介绍,本文只是提供了一种实现思路,代码仅供参考,需要的朋友可以了解看看,希望对大家有帮助,想要了解更多可以继续浏览群英网络其他相关的文章。
文本转载自脚本之家
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。