开发者

Writing an image from PIL's 'Image' class into a model instance's ImageFile field

开发者 https://www.devze.com 2023-02-11 03:36 出处:网络
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:

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()

    #Wha开发者_高级运维t 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)


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?:

0

精彩评论

暂无评论...
验证码 换一张
取 消