Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

working together with pillow? #57

Closed
mokko opened this issue Mar 6, 2021 · 5 comments
Closed

working together with pillow? #57

mokko opened this issue Mar 6, 2021 · 5 comments
Labels

Comments

@mokko
Copy link

mokko commented Mar 6, 2021

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
Copy link
Owner

LeoHsiao1 commented Mar 6, 2021

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
Copy link
Owner

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
Copy link
Owner

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

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

@mokko
Copy link
Author

mokko commented Mar 13, 2021 via email

@github-actions
Copy link

github-actions bot commented Aug 2, 2021

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

@github-actions github-actions bot locked and limited conversation to collaborators Aug 2, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

2 participants