20
votes

I'm going to let users upload images of 300x300 compressed with JPEG. Is there a way to determine what the maximum file size of such an image would be?

I can imagine this can be tried by compressing random noise at 100 quality, but is there a theoretical maximum?

Say that the image is totally uncompressable random noise, could it be 3 bytes per pixel (24-bits colour) and a margin for the metadata? Or could such an image turn out larger than the original when compressed?

2
Not an expert in this, but why not just use the size of an uncompressed bitmap (plus buffer for metadata?) as the largest you'll accept?Collin
@CollinHockey I thought about that but I thought that it could maybe become bigger ("Or could such an image..."). However, if that happens, it's probably not a lot so in practice that would likely be a good maximum to maintain.Bart van Heukelom

2 Answers

19
votes

From wikipedia:

For highest quality images (Q=100), about 8.25 bits per color pixel is required http://en.wikipedia.org/wiki/JPEG#Sample_photographs

So, for Q=100 on an 300x300 image, that would result in (300 * 300) px * 8.25 bits/px = 742,500 bits = ~ 93 kB

There are also lossless JPEG coding modes, which are practically not used (last sentence, second paragraph). But they would have the RGB typical 24 bits/pixel.

6
votes

There is no limit on jpeg metadata size, which means there's no limit to the size of a jpeg file. See this answer I've linked for an explanation of why and also for an example of a realistic situation where the metadata might get large: What is the maximum size of JPEG metadata?

So if assuming a maximum practical/realistic size suits your purpose, then you should factor that example into your calculations. In many contexts it would be fine to just reject things outside of that maximum as outside the domain of your program's intended usage.

But if you absolutely must rely on theoretical, then unfortunately it's a big bold

Note: I do not have a huge amount of personal experience with the jpeg specification, so I am going off of what people have said about repeated fields being allowed, as well as multiple comment fields. Please correct me if you find evidence to the contrary.