1

I have a website developed with Django 1.10. The users can send images to the website. Unfortunately there are images very heavy ! ( > 1 mo).

Currently when the dimension is greater or equal to 4000*4000, I resize to 128*128 but it's not sufficient for the weight...

Google advises to use Jpegoptim and Optipng. So I tried to use these tools directly in my Django code but it doesn't works... (I already install jpegoptim and optipng) :

def optimize(path):
    runString = {
        ".jpeg": u"jpegoptim -f --strip-all '%(file)s'",
        ".jpg": u"jpegoptim -f --strip-all '%(file)s'",
        ".png": u"optipng -force -o7 '%(file)s' && advpng -z4 '%(file)s' && pngcrush -rem gAMA -rem alla -rem cHRM -rem iCCP -rem sRGB -rem time '%(file)s' '%(file)s.bak' && mv '%(file)s.bak' '%(file)s'"
    }

    ext = splitext(path)[1].lower()
    if ext in runString :
        print("ok")
        subprocess.Popen(runString[ext] % {'file': path}, shell=True)


class ImageUser(models.Model):
    image = models.ImageField(upload_to="imageUser/", null=True)

    def save(self, *args, **kwargs) :
        super(ImageUser, self).save()
        image = Image.open(self.image.path)
        optimize(self.image.path)
        image.save(self.image.path)

I want to reduce the weight of the images before the saving if it's possible. Where I am wrong ? Thank you

Preumsse
  • 173
  • 1
  • 2
  • 7
  • And exactly *it* does not work *how*? What's the error message? What's the expected result you are not getting – dhke Nov 27 '16 at 12:08
  • 1
    And yeah: You call `optimize()` on the image path and then write the in-memory representation of `image` (which is probably from PIL or Pillow) back over that file *after* you called `optimize()`, essentially undoing anything the utilities did. – dhke Nov 27 '16 at 12:15
  • It does not work because the image weight stay the same. Ok but how can I get the image optimized ? – Preumsse Nov 27 '16 at 12:52
  • :up: :/ Can you help me ? – Preumsse Nov 27 '16 at 20:10
  • Try using this library for Django https://easy-thumbnails.readthedocs.io/en/latest/ – Most Wanted Sep 29 '21 at 07:04

0 Answers0