该方法是使用thinkphp框架自带的生成缩略图方法,把生成的缩略图根据定义的宽高各自存放。如果存在相同宽高、名称的缩略图,则不再生成新的缩略图。
1.在public\upload\里添加文件夹thumbnail来存放缩略图。
2.在\simplewind\cmf\common.php 的最后添加以下代码:
/**
* 生成缩略图 (不替换原图)
* @param $img 原图路径 路径格式: admin/20180101/xxxxxxx.png
* @param int $width 宽度
* @param int $height 高度
* @return string 返回可访问的图片路径
*/
function thumb( $img, $width=500, $height=500 ) {
ini_set('memory_limit', '300M'); //防止内存溢出(如果图片分辨率太高可能出现内存溢出)
if (empty($img)) return '';
if (strpos($img, "http") === 0 || strpos($img, "//") === 0 ) return $img;
$array = explode( '/', $img );
if ( count( $array ) != 3 ) return cmf_get_image_url( $img );
$imgName = explode('.', $array[count($array)]); //获取图片名称
if ( !file_exists( "./upload/$img" ) ) return '';//如果原图已丢失
$newName = $imgName[0] . "-$width-$height." . $imgName[1];
if ( file_exists( "./upload/thumbnail/$newName" ) ) {
//图片缩略图已存在
return cmf_get_image_url( "thumbnail/$width$height-$img_name" );
} else {
//生成缩略图
$image = \think\Image::open( ROOT_PATH . "/public/upload/$img" );
$image->thumb( $width, $height, 1)->save( "./upload/thumbnail/$newName", null, 100 );
return cmf_get_image_url( "/upload/thumbnail/$newName");
}
}
html调用例子: {:thumb($vo.thumbnail,600,600)}
关于ThinkPHP图片处理相关文档:https://www.kancloud.cn/manual/thinkphp5_1/354123
默认情况下,需要先执行composer require topthink/think-image来引入文件。
https://www.kancloud.cn/manual/thinkphp5_1/354123
注意:此方法并未核实测试。