php image类型怎么实现转换

发布时间:2022-05-25 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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视频教程》

以上就是php image类型怎么实现转换的详细内容,更多请关注脚本宝典其它相关文章

脚本宝典总结

以上是脚本宝典为你收集整理的php image类型怎么实现转换全部内容,希望文章能够帮你解决php image类型怎么实现转换所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:imageimagephp