0

So I looked at this question and got the following code from it:

import Image, ImageFile  
pic = pic/goes/here.jpg
im = Image.open(pic)
width, height = im.size
if width > 1000 or height > 1000:
    width = width*.7
    height = height*.7
im = im.resize((int(math.floor(width)), int(math.floor(height))), Image.ANTIALIAS)
try:
    im.save(pic,optimize=True,quality=80)
except IOError:
    ImageFile.MAXBLOCK = width * height
    im.save(pic,optimize=True,quality=80)

The last bit at the end came from this question as I noticed PIL just kind of gave up when the file exceeded around 1500~ px in size (I have no clue why?)

The problem is that when I run this code with a roughly 2500x1600 image PIL either gives me an image thats the same size (1.2MB) or an empty file with 0 MB. I once even got a file that was bigger!?!? (1.38MB)

So what am I doing wrong? I just want to optimize the image to as small of a file size without losing about 80% quality.

Also any other ways to reduce the file size in python? Thanks!!

Community
  • 1
  • 1
bnynn
  • 501
  • 1
  • 6
  • 20
  • 1
    After resetting the `ImageFile.MAXBLOCK` after an `IOError` you need to do another `im.save()` with it in effect. – martineau Dec 26 '13 at 02:38
  • Your code is incomplete; `pic` is not set anywhere. – Ramchandra Apte Dec 26 '13 at 03:04
  • Sorry! Didnt notice that I took this bit out of a function, its fixed now @martineau thanks! Im going to do a few more tests and that might be the issue – bnynn Dec 26 '13 at 03:12
  • You may not be enlarging `MAXBLOCK` enough. Recode the `im.save()` in a loop that incrementally increases the value several times before giving up. The goal is to make it big enough to read the entire image in at once so it can be optimized properly. – martineau Dec 26 '13 at 03:28
  • How silly! Thanks its fixed, I just forgot to put the im.save after maxblock thank you martineau, you should make an answer so I can give you holiday karma. ;D – bnynn Dec 26 '13 at 03:30
  • @bnynn: have you tried `Pillow` (`$ pip install pillow`)? [The bug might be fixed there](https://github.com/python-imaging/Pillow/issues/148) – jfs Dec 26 '13 at 13:14
  • 1
    Possible duplicate of [How to reduce the image file size using PIL](http://stackoverflow.com/questions/10607468/how-to-reduce-the-image-file-size-using-pil) – mgalardini Aug 12 '16 at 14:01

1 Answers1

1

I'm late here - but I noticed you have the quality set to 80. The default is 75. That could be the reason your file was larger.

Max Druiz
  • 69
  • 6