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

吾爱主题 阅读:142 2021-09-15 16:33:00 评论:0

需求

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

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

依赖

php扩展 gd 和 exif

实现

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 /**   * 图片格式转换   * @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' );      }    } }

使用

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://segmentfault.com/a/1190000020857436

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容