ChandimaPrabath commited on
Commit
4edb539
1 Parent(s): 29e070f

Upload image_payload_reader.py

Browse files
Files changed (1) hide show
  1. image_payload_reader.py +40 -0
image_payload_reader.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ import yaml
3
+
4
+ def read_payload_from_image(image_path):
5
+ """
6
+ Reads and extracts the YAML payload embedded in the PNG image metadata.
7
+
8
+ Args:
9
+ image_path (str): Path to the PNG image file.
10
+
11
+ Returns:
12
+ dict or None: Extracted YAML payload as a dictionary if found, None otherwise.
13
+ """
14
+ try:
15
+ # Open the image with Pillow
16
+ img = Image.open(image_path)
17
+
18
+ # Check if the image is a PNG and has metadata
19
+ if img.format == "PNG" and isinstance(img.info, dict) and "YAML" in img.info:
20
+ yaml_data = img.info["YAML"]
21
+
22
+ # Convert YAML string to dictionary
23
+ payload = yaml.safe_load(yaml_data)
24
+ return payload
25
+ else:
26
+ print("No YAML payload found in the PNG image metadata.")
27
+ return None
28
+ except Exception as e:
29
+ print(f"Error reading payload from image: {e}")
30
+ return None
31
+
32
+ # Example usage if executed directly (not necessary in the module version)
33
+ if __name__ == "__main__":
34
+ image_path = "cache/image_20240624111031.png" # Replace with the actual path to your PNG image file
35
+ payload = read_payload_from_image(image_path)
36
+ if payload:
37
+ print("Extracted YAML payload:")
38
+ print(yaml.dump(payload, default_flow_style=False))
39
+ else:
40
+ print("Failed to extract YAML payload.")