【问题标题】:Converting Base64 image to file return invalid image/data将 Base64 图像转换为文件返回无效图像/数据
【发布时间】:2017-06-10 19:56:34
【问题描述】:

在过去的两天里,我一直在尝试使用不同的方法将 base64 字符串转换为图像文件,但每次输出文件都没有显示图像(它确实显示了大小和一些编码数据)。

注意事项: 1. 浏览器将文件解释为文档而不是图像 mime,但我很确定这不是问题,因为我尝试在本地下载文件并且结果相同。 2.我尝试比较在线工具作为codebeautify.org/base64-to-image-converter的输出结果,因为图像文件中的数据似乎与我的数据不同。 3.目录和文件有775权限,apache有chown

此处为 Base64 字符串:https://dpaste.de/gP7D/raw

方法一:

list($type, $profile_image) = explode(';', $profile_image);
                list(,$extension) = explode('/',$type);
                list(,$profile_image)      = explode(',', $profile_image);
                if($extension == 'jpeg'){$extension = "jpg";}
                $filePath = '../uploads/profile_images/'.$uname.'.'.$extension; // using uname instead of unique id to not expose the uqniue key/session
                $profile_image = base64_decode($profile_image);
                file_put_contents($filePath, $profile_image);

方法B:

list($type, $profile_image) = explode(';', $profile_image);
                list(,$extension) = explode('/',$type);
                list(,$profile_image)      = explode(',', $profile_image);
                $filePath = '../uploads/profile_images/'.$uname.'.'.$extension;
                $ifp = fopen($filePath, 'wb');
                fwrite($ifp, base64_decode($profile_image));
                fclose($ifp);

我做错了什么?

更新: 显然,Apache/php.ini 的 max_input_vars 最大值为 5000,而我的 base64 字符串要高得多。该帖子可以标记为已解决。

【问题讨论】:

  • 如果提到的帖子中显示的方法对我不起作用并在此线程中说明,它是如何重复的?
  • 你是对的。你能与其余的代码分享一个要点吗?
  • 它是一个独立的函数。 $profile_image 存储 base64 字符串

标签: php image base64 image-conversion


【解决方案1】:

似乎您必须删除 base64 编码字符串的开头,这不是 base64 编码数据的一部分。 从 base64 字符串中删除 "data:image/jpeg;base64"

我做了一些简单的测试,得到了图像……

【讨论】:

  • "base64" 后面的逗号用于填充,不是字符串的一部分
  • 我建议您编写一些简单的调试代码...<?php $string = "[your encoded string]"; file_put_contents("test.jpg",base64_decode($string)); 然后检查您是否有一个可查看的文件...我用您的 base64 字符串完成了它并得到了一个工作 jpeg。
【解决方案2】:

Apache/Php.ini 文件的 max_input_vars 最大值为 5000,而我的 base64 字符串要高得多。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    相关资源
    最近更新 更多