你好,我想解码一个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文件
1条答案
按热度按时间f5emj3cl1#
我不知道出了什么问题,但你有流浪字符在您的文件
hash.txt
。你可以这样删除它们: