入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

php读取和保存base64编码的图片内容

创建时间:2016-01-25 投稿人: 浏览次数:1726
header("Content-type:text/html;charset=utf-8");
    //读取图片文件,转换成base64编码格式
    $image_file = "./picture.jpg";
    $image_info = getimagesize($image_file);
    $base64_image_content = "data:{$image_info["mime"]};base64," . 
    chunk_split(base64_encode(file_get_contents($image_file)));
    // string chunk_split ( string $body [, int $chunklen = 76 [, string $end = "
" ]] ) 将字符串分割成小块   
    // 使用此函数将字符串分割成小块非常有用。例如将 base64_encode() 的输出转换成符合 RFC 2045 语义的字符串。它会在每 chunklen 个字符后边插入 end

    //保存base64字符串为图片
    //匹配出图片的格式
    if (preg_match("/^(data:s*image/(w+);base64,)/", $base64_image_content,$result)){
          $type = $result[2];
          $new_file = "./test.{$type}";
          if (file_put_contents($new_file, base64_decode(str_replace($result[1], "", $base64_image_content)))){
                echo "新文件保存成功:", $new_file;
          }
    }

    echo "<pre>";
    print_r($result);
    echo "</pre>";
    echo "<pre>";
    print_r($result);
    echo "</pre>";

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。