You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Bitmap转Base64后Python解码存PNG失败求助

问题场景

Android端将Bitmap编码为Base64并写入hash.txt文件,Python中直接复制Base64字符串到变量可正常解码保存为PNG,但通过file.read()读取文件内容后解码失败。已尝试补充Base64 padding(添加==)、移除换行符等操作,问题仍存在。

Android编码相关代码
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;

Bitmap imageBitmap = (Bitmap) extras.get("data");
String encodedString = bitMapToBase64(imageBitmap);
AfterPictureBase64(encodedString);
Python解码代码
import base64
from PIL import Image
from io import BytesIO

def decode_base64_to_bitmap_and_save(base64_string, output_file_path):
    try:
        # Decode the base64 string to bytes
        decoded_bytes = base64.b64decode(base64_string)

        # Create a BytesIO stream from the decoded bytes
        byte_stream = BytesIO(decoded_bytes)

        # Open the image using Pillow (PIL)
        decoded_bitmap = Image.open(byte_stream)

        # Save the decoded bitmap as a PNG file
        decoded_bitmap.save(output_file_path, "PNG")

        return True  # Successful save
    except Exception as e:
        print(f"Error: {e}")
        return False  # Saving failed

# Example usage:
file_path = "hash.txt"
with open(file_path, "r") as file:
    base64_string = file.read()

output_file_path = "output.png"

if decode_base64_to_bitmap_and_save(base64_string, output_file_path):
    print(f"Image saved as {output_file_path}")
else:
    print("Failed to decode and save the image.")
解决方案
  • 统一编码与清理字符串:
    Python读取文件时指定UTF-8编码,并移除首尾空白、非法字符,自动补充正确的padding:

    import re
    import base64
    from PIL import Image
    from io import BytesIO
    
    def decode_base64_to_bitmap_and_save(base64_string, output_file_path):
        try:
            # 清理非法字符,只保留Base64合法字符
            base64_string = re.sub(r'[^A-Za-z0-9+/=]', '', base64_string)
            # 自动补充padding
            padding = len(base64_string) % 4
            if padding != 0:
                base64_string += '=' * (4 - padding)
            
            decoded_bytes = base64.b64decode(base64_string)
            byte_stream = BytesIO(decoded_bytes)
            decoded_bitmap = Image.open(byte_stream)
            decoded_bitmap.save(output_file_path, "PNG")
            return True
        except Exception as e:
            print(f"Error: {e}")
            return False
    
    # 修改读取逻辑
    file_path = "hash.txt"
    with open(file_path, "r", encoding="utf-8") as file:
        base64_string = file.read().strip()
    
    output_file_path = "output.png"
    if decode_base64_to_bitmap_and_save(base64_string, output_file_path):
        print(f"Image saved as {output_file_path}")
    else:
        print("Failed to decode and save the image.")
    
  • 修正Android端编码逻辑:
    确保bitMapToBase64方法无多余字符输出,使用Base64.NO_WRAP避免自动添加换行:

    private String bitMapToBase64(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        // 用NO_WRAP避免编码时插入换行符
        return Base64.encodeToString(byteArray, Base64.NO_WRAP);
    }
    

内容的提问来源于stack exchange,提问作者Ian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 19:52:42