kindeditor编辑器上传图片自动压缩(质量与尺寸压缩)附PHP代码

作者: unvs 分类: PHP 发布时间: 2019-06-20 12:18 ė13,441 views 6没有评论

 

kindeditor上传图片,仅仅只能设置上传的图片大小、图片数量限制,上传后图片是多大就是多大,很不方便,不能对图片进行相应压缩处理。下面就是博主写的一个函数,通过对上传图片质量压缩、尺寸压缩,直接减小图片大小,节省空间,提高图片加载速度。

kindeditor上传图片处理的关键文件是kindeditor\php\upload_json.php

找到这一行代码:
$file_url = $save_url . $new_file_name;

后面加上下面代码:

$file_url_ = $save_url .’-1′. $new_file_name;

compress_image($file_url,$file_url_);//压缩图片

再页面最后,添加compress_image压缩图片函数(通过质量压缩,尺寸压缩判断为大于750则进行等比例缩小)

/**
* 等比压缩图片-unvscn-2018.11.22
* @param [type] $oldFile 旧图片路径
* @param [type] $newFile 新图片路径
* @return [type] null
*/
function compress_image($oldFile,$newFile)
{
$oldFile = $_SERVER['DOCUMENT_ROOT'] . $oldFile;
$newFile = $_SERVER['DOCUMENT_ROOT'] . $newFile;
if(!is_dir($file_path = dirname($newFile))) mkdir($file_path,0777,true);
//判断是否是伪造的图片文件类型
//if (strpos($realType = mime_content_type($oldFile), ‘image/’) === false) return false;
//获取图片信息
$testImg = getimagesize($oldFile);
//判断是否是有效图片
if (!$testImg) return false;
//图片信息赋给变量
list($width, $height, $type, $attr) = $testImg;
//原图片信息
$oldImageInfo = array(
‘width’ => $width,
‘height’ => $height,
‘type’ => image_type_to_extension($type, false),
‘attr’ => $attr
);
//创建一个原图的图像实例
$fun = “imagecreatefrom” . $oldImageInfo['type'];
$oldImage = $fun($oldFile);
if ($oldImageInfo['width'] > 750) {
$newWidth = 750;
$newHeight = round(($newWidth * $oldImageInfo['height']) / $oldImageInfo['width'], 1);
} else {
$newWidth = $oldImageInfo['width'];
$newHeight = $oldImageInfo['height'];
}
//$newWidth = $oldImageInfo['width'];
//$newHeight = $oldImageInfo['height'];
//根据新的长宽尺寸创建新的画布
$imageThump = imagecreatetruecolor($newWidth, $newHeight);
//将原图复制带图片载体上面,并且按照一定比例压缩,极大的保持了清晰度
imagecopyresampled($imageThump, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $oldImageInfo['width'], $oldImageInfo['height']);
imagedestroy($oldImage);
$newImage = $imageThump;
//使用原图片的扩展名
//$funcs = “image”.$oldImageInfo['type'];
$funcs = “imagejpeg”;
//保存心创建的图片文件,由于与原文件同名,故可覆盖掉未压缩的原图
$newFile = $file_path.”\\”.basename($oldFile);
$funcs($newImage, $newFile);
imagedestroy($newImage);
}

本博文章基本上属于原创或收集整理,都是心血结晶。
欢迎转载分享,转载请注明出处,谢谢!
本文地址:kindeditor编辑器上传图片自动压缩(质量与尺寸压缩)附PHP代码

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Ɣ回顶部