zoukankan      html  css  js  c++  java
  • PHP 之将网络图片base64编码与解码

    一、效果图

     二、编码

    /**
     * 图片base64编码
     * @param string $img
     * @param bool $imgHtmlCode
     * @return string
     */
    function imgBase64Encode($img = '', $imgHtmlCode = true)
    {
        //如果是本地文件
        if (strpos($img, 'http') === false && !file_exists($img)) {
            return $img;
        }
        //获取文件内容
        $file_content = file_get_contents($img);
        if ($file_content === false) {
            return $img;
        }
        $imageInfo = getimagesize($img);
        $prefiex = '';
        if ($imgHtmlCode) {
            $prefiex = 'data:' . $imageInfo['mime'] . ';base64,';
        }
        $base64 = $prefiex . chunk_split(base64_encode($file_content));
        return $base64;
    }

    三、解码

    /**
     * 片base64解码
     * @param string $base64_image_content 图片文件流
     * @param bool $save_img 是否保存图片
     * @param string $path 文件保存路径
     * @return bool|string
     */
    function imgBase64Decode($base64_image_content = '', $save_img = false, $path = '')
    {
        if (empty($base64_image_content)) {
            return false;
        }
    
        //匹配出图片的信息
        $match = preg_match('/^(data:s*image/(w+);base64,)/', $base64_image_content, $result);
        if (!$match) {
            return false;
        }
    
        //解码图片内容(方法一)
        /*$base64_image = preg_split("/(,|;)/",$base64_image_content);
        $file_content = base64_decode($base64_image[2]);
        $file_type = substr(strrchr($base64_image[0],'/'),1);*/
    
        //解码图片内容(方法二)
        $base64_image = str_replace($result[1], '', $base64_image_content);
        $file_content = base64_decode($base64_image);
        $file_type = $result[2];
    
        //如果不保存文件,直接返回图片内容
        if (!$save_img) {
            return $file_content;
        }
    
        //如果没指定目录,则保存在当前目录下
        if (empty($path)) {
            $path = __DIR__;
        }
        $file_path = $path . "/" . date('Ymd', time()) . "/";
        if (!is_dir($file_path)) {
            //检查是否有该文件夹,如果没有就创建
            mkdir($file_path, 0777, true);
        }
        $file_name = time() . ".{$file_type}";
        $new_file = $file_path . $file_name;
        if (file_exists($new_file)) {
            //有同名文件删除
            @unlink($new_file);
        }
        if (file_put_contents($new_file, $file_content)) {
            return $new_file;
        }
        return false;
    }
  • 相关阅读:
    优化cocos2d/x程序的内存使用和程序大小
    cocos2d-x移植:xcode到eclipse
    程序员在编程工作中痛苦的压抑着自己某些强烈的情绪
    C++语言的一些问题
    基数排序-图非常清晰明了
    【Cocos2d-X(1.x 2.x) 修复篇】iOS6 中 libcurl.a 无法通过armv7s编译以及iOS6中无法正常游戏横屏的解决方法
    《C++ Primer》笔记-inline内联函数
    走出你的舒适区
    UDP广播与多播
    测试问题反馈需要包含内容总结
  • 原文地址:https://www.cnblogs.com/yang-2018/p/12843950.html
Copyright © 2011-2022 走看看