matthewwithanm / django-imagekit

Automated image processing for Django. Currently v4.0
http://django-imagekit.rtfd.org/
BSD 3-Clause "New" or "Revised" License
2.26k stars 276 forks source link

ProcessedImageField and calculating hash in upload_to #483

Open a1tus opened 5 years ago

a1tus commented 5 years ago

Hello. Consider the situation. We have a model with photo = ProcessedImageField(processors=[ResizeToFit(100, 100)]) and dynamic upload_to arg where path is calculated as md5 for the uploaded image (quite typical behaviour).

The problem is that md5 hash that is calculated is using instance.photo but it holds original uploaded image but not the one that was passed through processors.

Temp fix below kinda works.

class PatchedProcessedImageFieldFile(ImageFieldFile):
    def save(self, name, content, save=True):
        filename, ext = os.path.splitext(name)
        spec = self.field.get_spec(source=content)
        ext = suggest_extension(name, spec.format)
        new_name = '%s%s' % (filename, ext)
        content = generate(spec)

        # PATCH: set generated file so that upload_to could use it
        # (`content` is File object)
        content.name = new_name
        setattr(self.instance, self.field.name, content)

        return super(PatchedProcessedImageFieldFile, self).save(new_name, content, save)

class PatchedProcessedImageField(ProcessedImageField):
    attr_class = PatchedProcessedImageFieldFile

May be it should be added to the master branch?

vstoykov commented 5 years ago

I'm not sure if this patch will work with storages different than the local FS.

a1tus commented 5 years ago

All I do there is just set image field value with actual data. Don't quite get the point where it can fail, can you clarify please?