Keep pnginfo metadata for gallery (#3150)

* Keep pnginfo metadata for gallery

* add test to pil_to_file for keeping image metadata

* Update CHANGELOG.md

* formatting

---------

Co-authored-by: Abubakar Abid <abubakar@huggingface.co>
This commit is contained in:
wfng92 2023-02-10 02:20:50 +08:00 committed by GitHub
parent 1bc817a600
commit f92109621a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 23 additions and 13 deletions

View File

@ -9,6 +9,7 @@ No changes to highlight.
## Documentation Changes:
* Sort components in docs by alphabetic order by [@aliabd](https://github.com/aliabd) in [PR 3152](https://github.com/gradio-app/gradio/pull/3152)
* Changes to W&B guide by [@scottire](https://github.com/scottire) in [PR 3153](https://github.com/gradio-app/gradio/pull/3153)
* Keep pnginfo metadata for gallery by [@wfng92](https://github.com/wfng92) in [PR 3150](https://github.com/gradio-app/gradio/pull/3150)
## Testing and Infrastructure Changes:
No changes to highlight.

View File

@ -128,26 +128,25 @@ def save_array_to_file(image_array, dir=None):
return file_obj
def get_pil_metadata(pil_image):
# Copy any text-only metadata
metadata = PngImagePlugin.PngInfo()
for key, value in pil_image.info.items():
if isinstance(key, str) and isinstance(value, str):
metadata.add_text(key, value)
return metadata
def save_pil_to_file(pil_image, dir=None):
file_obj = tempfile.NamedTemporaryFile(delete=False, suffix=".png", dir=dir)
pil_image.save(file_obj)
pil_image.save(file_obj, pnginfo=get_pil_metadata(pil_image))
return file_obj
def encode_pil_to_base64(pil_image):
with BytesIO() as output_bytes:
# Copy any text-only metadata
use_metadata = False
metadata = PngImagePlugin.PngInfo()
for key, value in pil_image.info.items():
if isinstance(key, str) and isinstance(value, str):
metadata.add_text(key, value)
use_metadata = True
pil_image.save(
output_bytes, "PNG", pnginfo=(metadata if use_metadata else None)
)
pil_image.save(output_bytes, "PNG", pnginfo=get_pil_metadata(pil_image))
bytes_data = output_bytes.getvalue()
base64_str = str(base64.b64encode(bytes_data), "utf-8")
return "data:image/png;base64," + base64_str

View File

@ -63,6 +63,16 @@ class TestImagePreprocessing:
output_base64 = processing_utils.encode_pil_to_base64(img)
assert output_base64 == deepcopy(media_data.ARRAY_TO_BASE64_IMAGE)
def test_save_pil_to_file_keeps_pnginfo(self):
input_img = Image.open("gradio/test_data/test_image.png")
input_img = input_img.convert("RGB")
input_img.info = {"key1": "value1", "key2": "value2"}
file_obj = processing_utils.save_pil_to_file(input_img)
output_img = Image.open(file_obj)
assert output_img.info == input_img.info
def test_encode_pil_to_base64_keeps_pnginfo(self):
input_img = Image.open("gradio/test_data/test_image.png")
input_img = input_img.convert("RGB")