zoukankan      html  css  js  c++  java
  • PHPBase64格式编码图片

    base64_encode编码图片

    /**
     * 获取图片的Base64编码(不支持url)
     * @date 2017-02-20 19:41:22
     *
     * @param $img_file 传入本地图片地址
     *
     * @return string
     */
    function imgToBase64($img_file) {
    
        $img_base64 = '';
        if (file_exists($img_file)) {
            $app_img_file = $img_file; // 图片路径
            $img_info = getimagesize($app_img_file); // 取得图片的大小,类型等
    
            //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
            $fp = fopen($app_img_file, "r"); // 图片是否可读权限
    
            if ($fp) {
                $filesize = filesize($app_img_file);
                $content = fread($fp, $filesize);
                $file_content = chunk_split(base64_encode($content)); // base64编码
                switch ($img_info[2]) {           //判读图片类型
                    case 1: $img_type = "gif";
                        break;
                    case 2: $img_type = "jpg";
                        break;
                    case 3: $img_type = "png";
                        break;
                }
    
                $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码
    
            }
            fclose($fp);
        }
    
        return $img_base64; //返回图片的base64
    }
    
    
    //调用使用的方法
    $img_dir = dirname(__FILE__) . '/uploads/img/11213223.jpg';
    $img_base64 = imgToBase64($img_dir);
    echo '<img src="' . $img_base64 . '">';       //图片形式展示
    echo '<hr>';
    echo $img_base64;           //输出Base64编码

    base64_decode解码图片

    $base64_string= explode(',', $base64_string); //截取data:image/png;base64, 这个逗号后的字符
    $data= base64_decode($base64_string[1]);  //对截取后的字符使用base64_decode进行解码
    file_put_contents($url, $data); //写入文件并保存
  • 相关阅读:
    Design Pattern: Gof
    ZT --- extern "C"用法详解 2010-08-21 19:14:12
    OCR
    Linux strace命令
    wireshark esp
    https://sourceware.org/gdb/onlinedocs/gdb/Forks.html
    12306网上买火车票选择上中下铺的方法
    gdb调试有fork的程序
    named piped tcp proxy
    bash 提示用户输入 choice
  • 原文地址:https://www.cnblogs.com/xuanjiange/p/12091054.html
Copyright © 2011-2022 走看看