php如何实现图片格式转换
2023-06-13 09:17:07 时间
php实现图片格式转换的方法:
开发过程中总会遇到一些需求需要对图片格式进行转换。比如 gif转png,jpg转png
如最近使用某平台的图片文件识别,居然不支持gif格式,那么就需要将gif处理成png等。
依赖
php扩展 gd 和 exif
实现
/**
* 图片格式转换
* @param string $image_path 文件路径或url
* @param string $to_ext 待转格式,支持png,gif,jpeg,wbmp,webp,xbm
* @param null|string $save_path 存储路径,null则返回二进制内容,string则返回true|false
* @return boolean|string $save_path是null则返回二进制内容,是string则返回true|false
* @throws Exception
* @author klinson <klinson@163.com>
*/
function transform_image($image_path, $to_ext = 'png', $save_path = null)
{
if (! in_array($to_ext, ['png', 'gif', 'jpeg', 'wbmp', 'webp', 'xbm'])) {
throw new \Exception('unsupport transform image to ' . $to_ext);
}
switch (exif_imagetype($image_path)) {
case IMAGETYPE_GIF :
$img = imagecreatefromgif($image_path);
break;
case IMAGETYPE_JPEG :
case IMAGETYPE_JPEG2000:
$img = imagecreatefromjpeg($image_path);
break;
case IMAGETYPE_PNG:
$img = imagecreatefrompng($image_path);
break;
case IMAGETYPE_BMP:
case IMAGETYPE_WBMP:
$img = imagecreatefromwbmp($image_path);
break;
case IMAGETYPE_XBM:
$img = imagecreatefromxbm($image_path);
break;
case IMAGETYPE_WEBP: //(从 PHP 7.1.0 开始支持)
$img = imagecreatefromwebp($image_path);
break;
default :
throw new \Exception('Invalid image type');
}
$function = 'image'.$to_ext;
if ($save_path) {
return $function($img, $save_path);
} else {
$tmp = __DIR__.'/'.uniqid().'.'.$to_ext;
if ($function($img, $tmp)) {
$content = file_get_contents($tmp);
unlink($tmp);
return $content;
} else {
unlink($tmp);
throw new \Exception('the file '.$tmp.' can not write');
}
}
}
使用
// 转换后保存在test.png
transform_image($url, 'png', './test.png');
transform_image($filepath, 'png', './test.png');
// 转换后二进制结果直接返回
transform_image($url, 'png');
transform_image($filepath, 'png');
未经允许不得转载:肥猫博客 » php如何实现图片格式转换
相关文章
- 脚本Linux实现自动化执行PHP脚本(linux自动执行php)
- 的应用利用PHP中MySQL函数实现功能强大的数据库操作(php中mysql函数)
- PHP专业连接MySQL:实现快速代码.(php连接mysql数据库代码)
- 数据库PHP编程实现从Oracle数据库读取数据(php读取oracle)
- 「Linux下的PHP开发」(linux开发php)
- 让Linux帮助启动PHP服务(linux启动php)
- MySQL与PHP的连接:实现快速数据库访问(mysql连接php)
- PHP编写的MSSQL查询:实现可能性无限(php写mssql查询)
- 检查PHP Redis环境实现快速可靠性服务(检查php redis)
- Redis与PHP结合极致无限可能(redis 集合 php)
- 如何对PHP程序中的常见漏洞进行攻击
- PHP实现的汉字拼音转换和公历农历转换类及使用示例