ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

php图片格式转换方法

2021-11-30 18:01:41  阅读:144  来源: 互联网

标签:case string img 图片格式 转换方法 path php image IMAGETYPE


/**
 * 图片格式转换
 * @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
 */
function image_change($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');
        }
    }
}

标签:case,string,img,图片格式,转换方法,path,php,image,IMAGETYPE
来源: https://www.cnblogs.com/wekyun/p/15625336.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有