开发者

In python, how would I open a PIL or Imagemagick Image as a file

开发者 https://www.devze.com 2023-03-04 17:15 出处:网络
I\'m taking uploaded files which I can save to S3 using SimpleS3: from simples3.bucket import S3Bucket

I'm taking uploaded files which I can save to S3 using SimpleS3:

from simples3.bucket import S3Bucket
upload = request.POST['image']
s = S3Bucket("cdn", s3.access_key, s3.secret_key)
s.put(upload.filename, upload.file.read())

Somewhere between saving that as a file and uploading it I save the f开发者_开发知识库ile which is an image as a thumbnail using PIL or Imagemagick depending on what kind of image file was uploaded. The process there is to turn the File into an Image. My question is how do I open that Image as a file? I'm trying to upload the thumbnail to Amazon's S3 exactly as I do above. My code below is the idea of what I'm attempting:

thumb = self._im.copy() #where _im is the Image
s = S3Bucket("cdn", s3.access_key, s3.secret_key)
s.put(self.filename+ext, thumb)

I've tried with no success:

f = open(thumb, "rb")
s.put(self.filename+ext, f.read()

What does work, but is incredibly inefficient, is writing the file to the drive using the Image.save function and then opening it as a file:

thumb.save(self.filename+ext)
f = open(self.filename+ext, 'r')
s.put(self.filename+ext, f.read())


Figured it out:

from StringIO import StringIO
f = StringIO() 
thumb.save(f, ext) 
s.put(self.filename+ext, f.getvalue())


For ImageMagick case, if you are using PythonMagick, you can use underlying Blob class,

>>> from PythonMagick import Image, Blob
>>> image = Image("images/test_image.miff")
>>> image.magick("PNG")
>>> blob = Blob()
>>> image.write(blob)
>>> len(blob.data)
28282
>>> blob.data[0:20]
'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x94'
0

精彩评论

暂无评论...
验证码 换一张
取 消