numpy python base64将编码图像解码为PIL并保存为png

kmb7vmvb  于 2023-10-19  发布在  Python
关注(0)|答案(1)|浏览(123)

你好,我想解码一个base64字符串,这是一个图像,我用JavaScript编码的方式,我编码它是我把它变成一个位图,然后编码位图,现在我试图解码它在Python中,这是我做的,我有一个hash.txt文件,其中有base64数据,我复制文件,把它放在变量定义,它的作品,然后我尝试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.")

我试过f.read我试过+“==”到f.read添加填充我试过删除\n与“”所以我删除所有的\n从base64
这是编码文件

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文件

f5emj3cl

f5emj3cl1#

我不知道出了什么问题,但你有流浪字符在您的文件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')

相关问题