您好,我想解码一个Base64字符串,这是一个我用我编码的方式编码的图像,我将其转换为位图,然后对位图进行编码,现在我正在try 用Python对其进行解码,这就是我所做的.我有一个包含Base64数据的hash.txt文件,我复制该文件,将其放在变量定义中,它起作用了,然后我try f.read(),但失败了,这是代码

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.")

我try 了f.read我try 了f.read的+"=="以添加填充我try 用""删除\n所以我从Base64中删除了所有\n

这是编码文件

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);

this是Base64文件

推荐答案

我不知道哪里出了问题,但您的文件中有错误的字符hash.txt.

您可以按如下方式删除它们:

# Load base64-encoded image from disk
with open(hash.txt, "r") as file:
   data = file.read()

# Remove extraneous rubbish
decoded_bytes = base64.b64decode(data.replace('\\n', ''))

# Wrap in BytesIO and open as PIL Image
im = Image.open(BytesIO(decoded_bytes))

im.save('result.png')

enter image description here

Python相关问答推荐

Python -Polars库中的滚动索引?

Python -根据另一个数据框中的列编辑和替换数据框中的列值

替换字符串中的多个重叠子字符串

带条件计算最小值

如何记录脚本输出

从dict的列中分钟

Plotly Dash Creating Interactive Graph下拉列表

如何在TensorFlow中分类多个类

旋转多边形而不改变内部空间关系

使用Python查找、替换和调整PDF中的图像'

如何排除prefecture_related中查询集为空的实例?

LocaleError:模块keras._' tf_keras. keras没有属性__internal_'''

python sklearn ValueError:使用序列设置数组元素

递归函数修饰器

根据Pandas中带条件的两个列的值创建新列

获取PANDA GROUP BY转换中的组的名称

在Django中重命名我的表后,旧表中的项目不会被移动或删除

如何在Python中自动创建数字文件夹和正在进行的文件夹?

如何在python tkinter中绑定键盘上的另一个回车?

如何将验证器应用于PYDANC2中的EACHY_ITEM?