Skip to content

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

@alphaveneno

Description

@alphaveneno

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)

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions