当前位置:首页 > PHP教程 > php应用 > 列表

PHP简单实现图片格式转换(jpg转png,gif转png等)

发布:smiling 来源: PHP粉丝网  添加日期:2022-01-19 10:07:29 浏览: 评论:0 

这篇文章主要介绍了PHP简单实现图片格式转换(jpg转png,gif转png等),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。

需求

开发过程中总会遇到一些需求需要对图片格式进行转换。比如 gif转png,jpg转png

如最近使用某平台的图片文件识别,居然不支持gif格式,那么就需要将gif处理成png等。

依赖

php扩展 gd 和 exif

实现

  1. /** 
  2.  * 图片格式转换 
  3.  * @param string $image_path 文件路径或url 
  4.  * @param string $to_ext 待转格式,支持png,gif,jpeg,wbmp,webp,xbm 
  5.  * @param null|string $save_path 存储路径,null则返回二进制内容,string则返回true|false 
  6.  * @return boolean|string $save_path是null则返回二进制内容,是string则返回true|false 
  7.  * @throws Exception  
  8.  * @author klinson <klinson@163.com> 
  9.  */ 
  10. function transform_image($image_path, $to_ext = 'png', $save_path = null) 
  11. { 
  12.   if (! in_array($to_ext, ['png', 'gif', 'jpeg', 'wbmp', 'webp', 'xbm'])) { 
  13.     throw new \Exception('unsupport transform image to ' . $to_ext); 
  14.   } 
  15.   switch (exif_imagetype($image_path)) { 
  16.     case IMAGETYPE_GIF : 
  17.       $img = imagecreatefromgif($image_path); 
  18.       break; 
  19.     case IMAGETYPE_JPEG : 
  20.     case IMAGETYPE_JPEG2000: 
  21.       $img = imagecreatefromjpeg($image_path); 
  22.       break; 
  23.     case IMAGETYPE_PNG: 
  24.       $img = imagecreatefrompng($image_path); 
  25.       break; 
  26.     case IMAGETYPE_BMP: 
  27.     case IMAGETYPE_WBMP: 
  28.       $img = imagecreatefromwbmp($image_path); 
  29.       break; 
  30.     case IMAGETYPE_XBM: 
  31.       $img = imagecreatefromxbm($image_path); 
  32.       break; 
  33.     case IMAGETYPE_WEBP: //(从 PHP 7.1.0 开始支持) 
  34.       $img = imagecreatefromwebp($image_path); 
  35.       break; 
  36.     default : 
  37.       throw new \Exception('Invalid image type'); 
  38.   } 
  39.   $function = 'image'.$to_ext; 
  40.   if ($save_path) { 
  41.     return $function($img, $save_path); 
  42.   } else { 
  43.     $tmp = __DIR__.'/'.uniqid().'.'.$to_ext; 
  44.     if ($function($img, $tmp)) { 
  45.       $content = file_get_contents($tmp); 
  46.       unlink($tmp); 
  47.       return $content; 
  48.     } else { 
  49.       unlink($tmp); 
  50.       throw new \Exception('the file '.$tmp.' can not write'); 
  51.     } 
  52.   } 
  53. } 

使用

  1. // 转换后保存在test.png 
  2. transform_image($url, 'png', './test.png'); 
  3. transform_image($filepath, 'png', './test.png'); 
  4. // 转换后二进制结果直接返回 
  5. transform_image($url, 'png'); 
  6. transform_image($filepath, 'png');

Tags: PHP图片格式转换

分享到: