I would like to resize a picture to a specific file size. For example, no more than 200KB. What is the best approach to achieve this with C# .NET ?
Thanks !
A rough estimate is as follows:
size(KB) = (width * height * bitdepth) / (8 * 1024)
The file size is inflated a bit more due to file information (compression info, etc).
See How to resize an image in C# to a certain hard disk size
If you think about it, you aren't going to know the filesize of the image until after it's resized. So you've either got to perform a successive iteration of attempts and compare the file sizes afterwards or you could change your constraints to restrict images to a particular set of height and width dimensions.
If this is not a very important function, trial and error works well enough. Just assume that if you need to shrink the input to N * 100%
, you do so by scaling both dimensions by sqrt(N) * 100%
.
If it is important, you need to understand image compression technologies better. I'll assume JPG. It's an image format that achievs lossy compression by breaking the image down into 8x8 pixel blocks, DFT transforming them, throwing away small coefficients, and then compressing the resulting bitstream.
Now it follows that you can fiddle quite a bit with the quality level, how many of the small coefficients you throw away. You don't need to redo the (expensive) DFT for this. So if the file ends just slightly too large, you can throw away a few more coefficients and recompress. And if you were slightly to aggressive, then put back a few coeffecients and compress again. This is all fairly fast.
You can do quite alot with the Drawing.Image class in order to resize an image.
There are many questions on how to do that. Here is one.
In terms of the size - you will not know what the size is untill after the resize operation. The only way to be certain is to resize, check the result and if it is too large try resizing with lower quality. Repeat until done.
You can approximate the size if you know the dimensions and color depth, as described in the answers to this (identical?) question.