Frage

I just started using Django and Python and I'm trying to build a photo app. This script is generating thumbnails and I'd like to do that myself. Unfortunately I don't understand what StringIO() is doing. The Python Docs aren't very helpful to me in that case.

Can someone please explain to me what StringIO() does in this particular case?

From 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()
War es hilfreich?

Lösung

StringIO is a class which can be used as a file-like object. You can use it exactly as you would a regular file, except instead of the data being written to disk, it will be written to a buffer ( a string buffer ) in memory.

In this script it looks like the image is first saved to a StringIO memory buffer, and after that the value of the string is retrieved and passed to the constructor for ContentFile to create a new instance of ContentFile, which is then passed to the field save function.

I would presume that the reason the script is using StringIO is that the constructor for ContentFile takes in a string, and writting to and then reading a StringIO file is the easiest way to get the image contents represented as a string.

As a side note, I would like to suggest that you look at Django's ImageFile field type, it has been more than enough for my image related needs, and is more clear than going through StringIO and ContentFiles.

Andere Tipps

StringIO provides the ability to read and write to a string just like one would write to a file. This could make the coding more convenient, easier, or both.

It also lets you edit strings, unlike regular python strings.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top