重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

php实现图片格式转换的方法是什么

这篇文章将为大家详细讲解有关php实现图片格式转换的方法是什么,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

创新互联是一家专业提供城阳企业网站建设,专注与做网站、成都网站设计、H5网站设计、小程序制作等业务。10年已为城阳众多企业、政府机构等服务。创新互联专业网站建设公司优惠进行中。

php实现图片格式转换的方法:首先转换后保存在【test.png】,代码为【transform_image($url, 'png', './test.png')】;然后转换后二进制结果直接返回。

php实现图片格式转换的方法是什么

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 
 */
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实现图片格式转换的方法是什么就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


当前名称:php实现图片格式转换的方法是什么
本文URL:http://cqcxhl.com/article/jcghsh.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP