[英]In python, how would I open a PIL or Imagemagick Image as a file
I'm taking uploaded files which I can save to S3 using SimpleS3: 我正在获取可以使用SimpleS3保存到S3的上传文件:
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 file which is an image as a thumbnail using PIL or Imagemagick depending on what kind of image file was uploaded. 在将其另存为文件并将其上传之前,我会根据上传的图像文件类型使用PIL或Imagemagick将文件作为缩略图保存为缩略图。 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.
我正尝试像上面一样将缩略图上传到Amazon S3。 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: 确实有效,但效率极低的是使用Image.save函数将文件写入驱动器,然后将其作为文件打开:
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, 对于ImageMagick的情况,如果您使用的是PythonMagick,则可以使用基础的Blob类,
>>> 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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.