LeoHsiao1 / pyexiv2

Read and write image metadata, including EXIF, IPTC, XMP, ICC Profile.
GNU General Public License v3.0
197 stars 39 forks source link

working together with pillow? #57

Closed mokko closed 3 years ago

mokko commented 3 years ago

Hi Leo,

thanks for a wonderful module and maintaining it!

Is there a way that I can open an image from pillow directly without writing it to the disk first?

Thanks!

LeoHsiao1 commented 3 years ago

As far as I know, you can load the image into memory, then read and write the image from memory:

# Load the image into memory
import io
buf = io.BytesIO()
with open('1.jpg', 'rb') as f:
    buf.write(f.read())

# Open the image in pillow
from PIL import Image
with Image.open(buf) as img:
    img.load()[0, 0]

# Open the image in pyexiv2
import pyexiv2
buf.seek(0)
with pyexiv2.ImageData(buf.read()) as pyexiv2_img:
    pyexiv2_img.read_exif()

# Omit the write operation...

buf.close()

In addition, I found that Pillow lost metadata when it saved the image, for example by executing the following code:

with Image.open('1.jpg') as img:
    img.save('1.jpg', format="JPEG", quality=95)

To avoid losing metadata, you should back up the metadata before Pillow opens the image, and write the metadata after Pillow saves the image.

LeoHsiao1 commented 3 years ago

io.BytesIO doesn't support modification, so Pillow should save the image like this:

saved_buf = io.BytesIO()
with Image.open(buf) as img:
    img.save(saved_buf, format="JPEG", quality=95)
LeoHsiao1 commented 3 years ago

I was wrong, io.BytesIO supports modification, just truncate it:

buf.truncate(0)
buf.seek(0)
mokko commented 3 years ago

Thank you!

On Sat, Mar 13, 2021 at 9:44 AM LeoHsiao @.***> wrote:

I was wrong, io.BytesIO supports modification, just truncate it:

buf.truncate(0)buf.seek(0)

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/LeoHsiao1/pyexiv2/issues/57#issuecomment-797960884, or unsubscribe https://github.com/notifications/unsubscribe-auth/AACDG5B3RWDT7N6XF6IK2E3TDMQV7ANCNFSM4YWR3XTA .

github-actions[bot] commented 2 years ago

This issue has been automatically closed because there has been no activity for a month.