我刚开始使用Django和Python,我正在尝试构建一个照片应用程序。这个脚本正在生成缩略图,我想自己来做。不幸的是,我不明白StringIO()在做什么。在这种情况下,Python文档对我没什么帮助。在
有人能给我解释一下StringIO()在这个特殊情况下做什么?在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()