tags:

views:

167

answers:

4

Hi,

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 !

+2  A: 

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.

grenade
After checking several methods which get unsatisfactory results, I decided to constrain the width and the height :)
+1  A: 

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.

Oded
Sounds like a dumb way to do it, from a CompSci viewpoint.
MSalters
@MSalters How would you go about predicting the future, in a CompSci way, that is?
Oded
For starters, this is a one-sided successive approximation algoritm (there's no check for too small output/bad quality). Therefore it's either slow or subject to overshoot. The second problem is that if you don't hit the target on your first attempt, you'll have to redo everything.
MSalters
+1  A: 

See How to resize an image in C# to a certain hard disk size

SwDevMan81
Cool, there's a couple good examples for estimating the filesize based on dimensions.
grenade
A: 

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.

MSalters