简体   繁体   中英

How to load an image in python without using disk storage?

I am writing a flask application that receives two image URLs as parameters. Traditionally, I would download this images on the server local disk and carry out my image processing operations. I am downloading them using following code.

urllib.request.urlretrieve(image1url, image_id + '.jpg')

After this I read the image using :

original_image = Image.open(image_id + '.jpg')

and carry out my Image Processing operations like crop and applying a few filters.

original_crop = original_image.crop((x, y, x + width / 3, y + height / 3))

Also, I use ImageFilter operations on this image. Now this code will be deployed on a server. If i continue this way I will keep downloading and saving images on the disk of the server. Of course, I understand that deleting the images after I am done with my Image Processing operations is one option. But if I get a few 100 calls per second, I might at some point of time use up a lot of space. The application is multi threaded using the call

app.run(threaded=true)

which works like a charm.

I want to know if there is a way to load an image without using disk storage of the server. Thus reducing the hard disk space requirements of my service.

if you don't want to store images in temporary files you can wrap URL content in stream and pass it to Image.open

import io
import urllib.request

from PIL import Image

# your avatar URL as example
url = ('https://www.gravatar.com/avatar/3341748e9b07c9854d50799e0e247fa3'
       '?s=328&d=identicon&response=PG&f=1')
content = urllib.request.urlopen(url).read()
original_image = Image.open(io.BytesIO(content))

You could move them to a known remote location and fetch them back as needed. Using Amazon S3 or a hosted FTP service like BrickFTP are both easy. S3 is especially cheap since you only pay for what you use -- no monthly fee. Brick is a great service if you want to make access to the images as simple as possible for other applications and users but there is a minimum monthly fee.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM