【问题标题】:PHP base64_docode saves corrupt imagePHP base64_decode 保存损坏的图像
【发布时间】:2016-02-18 05:45:10
【问题描述】:

我正在从我的 android 应用程序向 PHP 发送 base64 编码图像。有时它存储完整图像(4KB)和有时(3KB)(相同图像)。当我在 picasso 中使用 URL 时,4KB 大小的图像工作正常,但 3KB 大小的图像无法加载它显示解码错误。 这是我的 PHP 代码(有时可以)

$encodedImage = str_replace(' ','+',$_POST['encodedProfileImage']);
$data = base64_decode($encodedImage);
$file = 'Pics/'. uniqid() . '.png';
$success = file_put_contents($file, $data);
$BASE_URL = 'http://domain.com/TestApp/';

然后我在 PHP 中执行 SQL 操作来存储图像路径。是否有可能对半解码图像(已损坏)进行下一个代码操作。

【问题讨论】:

    标签: php android image base64


    【解决方案1】:

    您需要删除图像数据开头的data:image/png;base64 部分。之后才是真正的 base64 数据。

    使用以下函数:-

    function base64_to_png($base64_string, $output_file) {
        $ifp = fopen($output_file, "wb"); 
    
        $data = explode(',', $base64_string);
    
        fwrite($ifp, base64_decode($data[1])); 
        fclose($ifp); 
    
        return $output_file; 
    }
    

    如果你想使用str_replace 函数,那么可能会在下面工作。我不确定:)

    $fname = filter_input(INPUT_POST, "name");
    $encodedImage = filter_input(INPUT_POST, "image");
    $encodedImage = str_replace('data:image/png;base64,', '', $encodedImage);
    $encodedImage = str_replace(' ', '+', $encodedImage);
    $encodedImage = base64_decode($encodedImage);
    file_put_contents($fname, $encodedImage);
    print "Image has been saved!";
    

    希望对你有帮助:)

    【讨论】:

    • 但有时它会存储好的图像..但有时会损坏。 data:image/png;base64 这样做了吗?我可以用这个吗..$encodedImage = str_replace('data:image/png;base64','',encodedImage );
    • 我能再问一件事吗.. 在服务器上保存后$file = 'Pics/'. uniqid() . '.png'; file_put_contents($file, $data); 如何从 PHP 重命名文件名。 @ravi-hirani
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 2020-06-09
    • 2021-09-26
    • 1970-01-01
    相关资源
    最近更新 更多