1

I'm using ImageMagick and the binding wand to generate thumbnails for uploaded images in Django. I can generate the thumbnail fine, but I'm uncertain about how to go about passing the image object from ImageMagick back into the Django model. So I have a simplified model as below:

from wand import Image

class Attachment(models.Model):
    attachment = models.FileField(upload_to="some_path")
    thumbnail = models.ImageField(upload_to="other_path")

    def generate_thumb(self):
        with Image(file=self.attachment) as wand:
            thumb = wand.resize(width=50, height=50)
            thumb.save(file=self.thumbnail)

This generates an error at the last line of ValueError: The 'thumbnail' attribute has no file associated with it. Is there a simple way to get a file object out of wand and into django without too much silliness?

Thanks.

minhee
  • 5,688
  • 5
  • 43
  • 81
TimD
  • 1,371
  • 3
  • 12
  • 20
  • How do you use the 'generate_thumb' function? There is probably another place in your code with a reference to it. – sergzach Aug 15 '12 at 15:56

2 Answers2

5

Disclaimer: I am the creator of Wand you are trying to use.

First of all, ImageField requires PIL. It means you don’t need Wand, because you probably already installed an another image library. However I’ll answer to your question without any big changes.

It seems that self.thumbnail was not initialized yet at the moment, so you have to create a new File or ImageFile first:

import io

def generate_thumb(self):
    buffer = io.BytesIO()
    with Image(file=self.attachment) as wand:
        wand.resize(width=50, height=50)
        wand.save(file=buffer)
    buffer.seek(0)
    self.thumbnail = ImageFile(buffer)

Plus, from wand import Image will raise ImportError. It should be changed:

from wand.image import Image
minhee
  • 5,688
  • 5
  • 43
  • 81
  • Thank you for this; although I was fighting with using the PIL version of ImageFile. As most would know, I should have been usingthe django wrapper: from django.core.files.images import ImageFile – Zach Oct 14 '14 at 21:16
2

If the goal is easy thumbnails in your django app try: https://github.com/sorl/sorl-thumbnail

Its pretty popular and active.

Francis Yaconiello
  • 10,829
  • 2
  • 35
  • 54