PHP源码编写
<?php ini_set('display_errors',1); class imagick_convert { //原始图片绝对路径 private $str_old_file = ''; //转换webp默认扩展名 private $str_default_ext = 'webp'; //支持转换的图片格式 private $arr_image_ext = null;
public function __construct($str_image_path) { $this->str_old_file = $str_image_path; }
public function convert_transform_images($webp_dir = '') { //文件是否存在 if(!is_file($this->str_old_file)) { //WEBP格式转换:待转换的图片路径不正确 return $this->str_old_file; } //图片基本信息 $ext = pathinfo($this->str_old_file,PATHINFO_EXTENSION); $ext = empty($ext) ? '' : strtolower($ext); //图片质量 $this->arr_image_ext = array( 'jpeg' => Imagick::COMPRESSION_JPEG, 'jpg' => Imagick::COMPRESSION_JPEG, 'png' => Imagick::COMPRESSION_UNDEFINED, ); //根据后缀名把jpg或者png转成webp if(!in_array($ext, array_keys($this->arr_image_ext))) { //WEBP格式转换:暂不支持该格式转换,目前仅支持转换 jpeg,jpg和png 格式 return $this->str_old_file; } //默认webp图片新路径 if(empty($webp_dir)) { $webp_dir = rtrim($this->str_old_file,$ext) . $this->str_default_ext; } //开始转换 try { //原图的质量 $new_q = $this->get_img_quality($ext); //转换成webp格式 $this->do_jpg_transform_webp($webp_dir, $new_q); } catch(Exception $e) { //WEBP格式转换:工具转换异常,切换至GD库转换 $webp_dir = $this->php_gd_image_webp($ext,$webp_dir); } //睡眠0.2秒 usleep(20000); if(is_file($webp_dir)) { //删除原始图片 + 设置WEBP图片访问权限 chmod($webp_dir, 0777); unlink($this->str_old_file); //WEBP格式转换:转换成功 return $webp_dir; } //WEBP格式转换:转换失败,返回原始图片路径 return $this->str_old_file; }
private function get_img_quality($str_ext) { $resource = new Imagick($this->str_old_file); //png特殊处理 if($str_ext == 'png') { $resource->setImageFormat('PNG'); } $resource->setImageCompression($this->arr_image_ext[$str_ext]); $current = $resource->getImageCompressionQuality(); $resource->clear(); $resource->destroy(); if(!isset($current) || empty($current)) { $current = 80; } $resource->clear(); $resource->destroy(); return $current; }
private function do_jpg_transform_webp($webp_img_path, $int_q = 80) { exec("cwebp -q {$int_q} {$this->str_old_file} -o {$webp_img_path}"); }
private function php_gd_image_webp($ext,$webp_img_path) { //jpg处理使用jpeg $ext = $ext == 'jpg' ? 'jpeg' : $ext; //拼接函数名 imagecreatefromjpeg 还是 imagecreatefrompng $funName = 'imagecreatefrom' . $ext; //开始转换 $obj_img = null; try { //打开这个图片资源 $obj_img = $funName($this->str_old_file); //用这个图片资源创建一个webp图片, 存在路径$tdir imagewebp($obj_img,$webp_img_path); } catch(Exception $e) {
} //销毁画布资源 if($obj_img != null) { imagedestroy($obj_img); } //睡眠0.3秒 return $webp_img_path; } }