zoukankan      html  css  js  c++  java
  • php 图片格式转换-亲测ok

    代码如下

    /**
     * 图片格式转换
     * @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');
            }
        }
    }
  • 相关阅读:
    linux 计划任务
    linux 进程管理
    PHP中global与$GLOBALS['']的区别
    php预定义变量
    linux 强制终止进程命令
    mysql取某表中数据的随机的方法
    mysql 连接 选库 查询
    Python 的异步 IO:Asyncio 简介
    并发和并行的区别
    asyncio模块中的Future和Task
  • 原文地址:https://www.cnblogs.com/pxjbk/p/12060438.html
Copyright © 2011-2022 走看看