Edgar Navasardyan
Edgar Navasardyan

Reputation: 4501

Reducing an image byte size to given value for format other than jpeg

Following this post, I successfully reduced the byte size of an image to the desired level, but the problem is that I succeeded to do that only for JPEG. When I try to perform this for, say, png, the function does not do what is expected:

def get_highest_acceptable_quality(image, filename, target):
    q_min, q_max = 1, 96
    # Highest acceptable quality found
    q_acc = -1
    while q_min <= q_max:
        m = math.floor((q_min + q_max) / 2)
        buffer = BytesIO()
        image.save(buffer, format="png", compress_level=m) 
        s = buffer.getbuffer().nbytes # the s value is always the same for all values of m

        ...

The strange thing here is that the value of s remains the same irrespective of what the value of m is. Which is not the case for JPEG (here the entire function works just fine). I am completely lost because I am not a pro in image processing stuff. Any help?

Upvotes: 1

Views: 220

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207455

JPEG is lossy. That means it is permitted to change your image pixels in order to reduce your filesize, i.e. you trade absolute accuracy for a decrease in size and transmission time. It tries to take advantage of the way we see things in order to make the quality loss less noticeable. For the technically inquisitive, I am referring to "chroma subsampling" whereby the colour information is sub-sampled because the human eye is more sensitive to brightness variation than to colour variation, and to "quantisation" whereby high frequency changes are weighted less or discarded because the human eye is better at seeing changes over a broader area than making out thousands of changes in a small, dense, confused area - see Wikipedia article on JPEG.

PNG, on the other hand, is always lossless. It cannot discard information or change pixels to make filesize smaller. Ultimately that means, with certain image types, it cannot reduce filesizes as far as JPEG.

Upvotes: 2

Related Questions