温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php image类型如何实现转换

发布时间:2021-12-27 11:02:30 来源:亿速云 阅读:110 作者:iii 栏目:编程语言

本篇内容主要讲解“php image类型如何实现转换”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“php image类型如何实现转换”吧!

php image类型实现转换的方法:1、创建一个PHP示例文件;2、通过“function image_change($image_path, $to_ext = 'png',$save_path=null){...}”方法实现转换即可。

php image类型如何实现转换

本文操作环境:Windows7系统,PHP7.1版,Dell G3电脑。

php image类型怎么实现转换?

php图片格式转换方法

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

到此,相信大家对“php image类型如何实现转换”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI