How can I save an image as a PNG or JPG file with a given output file size? (pref. in C#)

StackOverflow https://stackoverflow.com/questions/421056

  •  05-07-2019
  •  | 
  •  

Question

I'd like to save an existing image as a PNG or JPG at a given file size, eg, 100KB.

Was it helpful?

Solution

PNG uses lossless compression so you can not compress it below a certain level.

In .NET you can save a JPG with compression, and guess how big the file will be when completed.

http://msdn.microsoft.com/en-us/library/system.drawing.image.save(VS.80).aspx - See the "Save JPEG image with compression value" section.

Also, you could resize the image dimensions to make it smaller.

OTHER TIPS

Only if using JPG 2000 you could set the file size to a specific value. Using JPG, you'll have to try different quality values and using PNG will get you one size for a given image and a compression level - you can only try to resize the image which will give you a smaller size.

You could also try to resize the image so that an uncompressed image would have the size you want, but then PNG and especially JPG will often have a much lower file size.

For PNG there isn't really a quality setting, so you can't really control the file size.

Jpg has a quality setting that determines how good a quality the image will be. lower quality settings result in smaller files. However, there is normally no option for "give the quality needed for a file of size x".

You can achieve the same result using a rather inefficient approach of converting to jpg in memory, seeing how big the output is, adjusting the quality up or down and repeating until you get close enough. It might sound terrible, but if your images aren't too big you may find no one notices the short delay while you do this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top