Search code examples
pythonpython-3.xnumpybase64python-imaging-library

python base64 decoding encoded image to PIL and saving it as png


Hello I want to decode a base64 string that is an image that I have encoded using JavaScript the way I encoded it was I turned it into a bitmap then encoded the bitmap now I am trying to decode it in python and this is what I did I have a hash.txt file that has base64 data in it I copy the file place it in the variable definition and it works then I try f.read() and it fails this is the code

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

I tried f.read i tried the + "==" to the f.read to add padding i tried to remove the \n with "" so i remove all the \n from the base64

this is the encoding file

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

and this is the base64 file


Solution

  • I'm not sure what went wrong but you have stray characters in your file hash.txt.

    You can delete them like this:

    # 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