fix(webp): failed to save metadata for webp

This commit is contained in:
arkohut 2024-08-23 18:25:19 +08:00
parent ea3cd2e66e
commit 420d972513

View File

@ -19,7 +19,10 @@ def write_image_metadata(image_path, metadata):
metadata_info.add_text("Description", json.dumps(metadata))
img.save(image_path, "PNG", pnginfo=metadata_info)
elif image_path_str.lower().endswith(".webp"):
img.save(image_path, "WebP", quality=85, metadata=json.dumps(metadata))
# Convert metadata to bytes
metadata_bytes = json.dumps(metadata).encode('utf-8')
# Use exif parameter to save metadata
img.save(image_path, "WebP", exif=metadata_bytes, quality=85)
else:
print(f"Skipping unsupported file format: {image_path_str}")
@ -35,19 +38,24 @@ def get_image_metadata(image_path):
)
try:
return json.loads(existing_description.decode("utf-8"))
except json.JSONDecodeError:
except json.JSONDecodeError as e:
print(f"Error decoding JSON metadata for {image_path_str}: {e}")
return {}
elif image_path_str.lower().endswith(".png"):
existing_description = img.info.get("Description", "{}")
try:
return json.loads(existing_description)
except json.JSONDecodeError:
except json.JSONDecodeError as e:
print(f"Error decoding JSON metadata for {image_path_str}: {e}")
return {}
elif image_path_str.lower().endswith(".webp"):
existing_metadata = img.info.get("metadata", "{}")
existing_metadata = img.info.get("exif", b"{}")
try:
if isinstance(existing_metadata, bytes):
existing_metadata = existing_metadata.decode('utf-8')
return json.loads(existing_metadata)
except json.JSONDecodeError:
except json.JSONDecodeError as e:
print(f"Error decoding JSON metadata for {image_path_str}: {e}")
return {}
else:
print(f"Unsupported file format: {image_path_str}")