kindeditor是一款开源编辑器,在web网站编辑领域使用非常多,自带的编辑器代码只能限制大小,不能限制图片宽高,有时候图片太宽了非常难看,这篇文章介绍kindeditor编辑器上传图片超宽自动压缩,等比压缩,直接减小图片大小,节省空间,提高图片加载速度。
找到下面文件并打开,kindeditor\php\upload_json.php
找到这一行代码:
$file_url = $save_url . $new_file_name;
后面加上下面代码:
compressedImage($_SERVER['DOCUMENT_ROOT'].$file_url,800);//压缩图片
上面这个代码,还可以设置压缩质量,具体功能可以查看下面函数
然后再文件底部,加入下面2个函数
/**
* desription 等比压缩图片 作者wfuyu.com
* @param sting $imgsrc 图片路径
* @param string $imgdst 压缩后保存路径,如果为空,则覆盖
,$zhiliang=90 图片质量
$wd=如果超过这个尺寸就等比压缩
*/
function compressedImage($imgsrc,$wd=600,$zhiliang=90,$imgdst=''){
if($imgdst==''){$imgdst=$imgsrc;}
list($width, $height, $type) = getimagesize($imgsrc);
$new_width = $width;//压缩后的图片宽
$new_height = $height;//压缩后的图片高
if($width >= $wd){
$per = $wd / $width;//计算比例
$new_width = $width * $per;
$new_height = $height * $per;
}
switch ($type) {
case 1:
$giftype = check_gifcartoon($imgsrc);
if ($giftype) {
// header('Content-Type:image/gif');
$image_wp = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromgif($imgsrc);
$bg =imagecolorallocate($image_wp, 255, 255, 255);
imagefill($image_wp, 0, 0, $bg);
imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
//90代表的是质量、压缩图片容量大小
imagejpeg($image_wp, $imgdst, $zhiliang);
imagedestroy($image_wp);
imagedestroy($image);
}
break;
case 2:
// header('Content-Type:image/jpeg');
$image_wp = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($imgsrc);
imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
//90代表的是质量、压缩图片容量大小
imagejpeg($image_wp, $imgdst, $zhiliang);
imagedestroy($image_wp);
imagedestroy($image);
break;
case 3:
//header('Content-Type:image/png');
$image_wp = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefrompng($imgsrc);
$bg =imagecolorallocate($image_wp, 255, 255, 255);
imagefill($image_wp, 0, 0, $bg);
imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
//90代表的是质量、压缩图片容量大小
imagejpeg($image_wp, $imgdst, $zhiliang);
imagedestroy($image_wp);
imagedestroy($image);
break;
}
}
function check_gifcartoon($image_file){ $fp = fopen($image_file,'rb');$image_head = fread($fp,1024);fclose($fp);return preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$image_head)?false:true;}