Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

def decode_and_save_image(json_file_path, output_image_path) does not return a valid PNG file #149

Open
alphaveneno opened this issue Oct 28, 2024 · 0 comments
Assignees

Comments

@alphaveneno
Copy link

This from the runpod tutorial:

https://docs.runpod.io/tutorials/serverless/gpu/run-your-first#get-your-results

There are three problems with the code at the end of this page:

  1. this line of code gives a KeyError:

base64_image = data["output"][0]["image"]

Note the structure of output.json - that comes from running the tutorial code as instructed - to see why there is a KeyError:

{
"delayTime": 1704,
"executionTime": 12336,
"id": "dbb15525-6d69-41fb-a69a-b7a5ec9ff8a1-u1",
"output": {
"image_url": "data:image/png;base64,iVBORw0KGgoA .....",
"images": [
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA ....."
],
"seed": 16076
},
"status": "COMPLETED",
"workerId": "zaxen2j2wld52g"
}

  1. the ASCII string that is returned as 'base64_image' should be of a length that is a multiple of 4, it is not always so.

  2. the ASCII string does not render a valid PNG file because it has the prefix "data:image/png;base64" (see above)

#################################################

This is my corrected version of the code, which returns a valid PNG file:

import json
import base64
import binascii

def decode_and_save_image(json_file_path, output_image_path):

    try:
        # Reading the JSON file
        with open(json_file_path, "r") as file:
            data = json.load(file)

        # Extracting the base64 encoded image data
        base64_image = data["output"]["images"][0]

        # Remove the data URL prefix 
        base64_image = base64_image.replace("data:image/png;base64,", "") 
        
        # Pad the string with "=" to make its length a multiple of 4 
        padding = 4 - (len(base64_image) % 4) 
        base64_image += "=" * padding 
        
        # Decode and write to a PNG file
        image_data = base64.b64decode(base64_image)
        
        with open("decoded_image.png", "wb") as f:
            f.write(image_data) 

        print(f"Image successfully decoded and saved as '{output_image_path}'.")

    except FileNotFoundError:
        print(
            "File not found. Please ensure the JSON file exists in the specified path."
        )
    except KeyError as e:
        print(f"Error in JSON structure: {e}")
    except binascii.Incomplete as e:
        print(f"Incomplete data: {e}")
    except binascii.Error as e:
        print(f"Programming or Padding error: {e}")
    except Exception as e:
        print(f"An error occurred: {e}")


# Usage

json_file_path = "./output.json"  # Path to your JSON file
output_image_path = "./decoded_image.png"  # Desired path for the output image

decode_and_save_image(json_file_path, output_image_path)
@alphaveneno alphaveneno changed the title def decode_and_save_image(json_file_path, output_image_path) does not reurn a valid PNG file def decode_and_save_image(json_file_path, output_image_path) does not return a valid PNG file Oct 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants