1

I want to load an image and manipulate it using Python Imaging Library and then store it in a model's ImageField. The following outlines what I'm trying to do, minus the manipulation:

#The model

    class DjInfo(models.Model):
        dj_name = models.CharField(max_length=30)
        picture = models.ImageField(upload_to="images/dj_pictures")
        email_address = models.EmailField()

    #What I'm trying to do:

    import tempfile
    import Image
    from artists.models import DjInfo

    image = Image.open('ticket.png')
    tf = tempfile.TempFile(mode='r+b')
    image.save(tf, 'png')

    dji=DjInfo()
    dji.picture.save('test.png', tf)
Alex
  • 23
  • 6

1 Answers1

-1

You could do this:

image = Image.open('test.png')
tf = tempfile.TemporaryFile(mode='r+b')
name = tf.name
del tf
image.save(name, 'png')
dji=DjInfo()
dji.picture.save('test.png', name)

But I suspect there is a better way using cStringIO or some other buffer object saving the extra step of writing a temp file to HDD.

Is this the same question?:

Community
  • 1
  • 1
Paul
  • 42,322
  • 15
  • 106
  • 123
  • 1
    I think you're misusing tempfile.TemporaryFile there: it's supposed to provide you with an actual file object for reading and writing to, which is deleted when closed/garbage-collected. You appear to be using it to generate the name for a temporary file, which you *could* use tempfile.NamedTemporaryFile for, though again, that would be a mis-use. I didn't actually get it to work with tempfile, though I could get it to work by doing the tempfile work 'manually', so I'll go down that route. Many thanks for looking though and thank you for pulling up the other q - could be v useful. – Alex Feb 19 '11 at 14:51
  • Turns out the link you dug up detailed how to do it in-memory, which is even better than tempfiles (in my case - not large images). Thanks again! – Alex Feb 19 '11 at 19:50
  • I agree it's a misuse of tempfile.. mostly. At least you are using it to find a collision-less file to write to. I was in a rush when I wrote the answer and I even forgot to unlink the temporary file. – Paul Feb 19 '11 at 22:32
  • Either way - your superior searching skills solved my problem so I'm happy. Thanks again! – Alex Feb 20 '11 at 01:54