我刚开始使用 Django 和 Python,我正在尝试构建一个照片应用程序。这个脚本正在生成缩略图,我想自己做。不幸的是,我不明白StringIO()
在做什么。在这种情况下,Python 文档对我没有多大帮助。
有人可以向我解释StringIO()
在这种特殊情况下会做什么吗?
来自http://djangosnippets.org/snippets/1172/:
def save(self):
from PIL import Image
#Original photo
imgFile = Image.open(self.image.path)
#Convert to RGB
if imgFile.mode not in ('L', 'RGB'):
imgFile = imgFile.convert('RGB')
#Save a thumbnail for each of the given dimensions
#The IMAGE_SIZES looks like:
#IMAGE_SIZES = { 'image_web' : (300, 348),
# 'image_large' : (600, 450),
# 'image_thumb' : (200, 200) }
#each of which corresponds to an ImageField of the same name
for field_name, size in self.IMAGE_SIZES.iteritems():
field = getattr(self, field_name)
working = imgFile.copy()
working.thumbnail(size, Image.ANTIALIAS)
fp = StringIO()
working.save(fp, "JPEG", quality=95)
cf = ContentFile(fp.getvalue())
field.save(name=self.image.name, content=cf, save=False);
#Save instance of Photo
super(Photo, self).save()