High quality JPEG compression with c#

The .Net encoder built-in to the library (at least the default Windows library provided by Microsoft) is pretty bad:

http://b9dev.blogspot.com/2013/06/nets-built-in-jpeg-encoder-convenient.html

Partial Update

I’m now using an approach outlined here, that uses ImageMagick for the resize then jpegoptim for the final compression, with far better results. I realize that’s a partial answer but I’ll expand on this once time allows.

Older Answer

ImageMagick is the best choice I’ve found so far. It performs relatively solid jpeg compression.

http://magick.codeplex.com/

It has a couple downsides:

  1. It’s better but not perfect. In particular, its Chroma subsampling is set to high detail at 90% or above, then jumps down to a lower detail level – one that can introduce a lot of artifacts. If you want to ignore subsampling, this is actually pretty convenient. But if you wanted high-detail subsampling at say, 50%, you have a larger challenge ahead. It also still won’t quite hit quality/compression levels of Photoshop or Google PageSpeed.

  2. It has a special deployment burden on the server that’s very easy to miss. It requires a Visual Studio 2008 SDK lib installed. This lib is available on any dev machine with Visual Studio on it, but then you hit the server for the first time and it implodes with an obscure error. It’s one of those lurking gotchas most people won’t have scripted/automated, and you’ll trip over it during some future server migration.

Oldest Answer

I dug around and came across a project to implement a C# JPEG encoder by translating a C project over:

http://www.codeproject.com/Articles/83225/A-Simple-JPEG-Encoder-in-C

which I’ve simplified slightly:

https://github.com/b9chris/ArpanJpegEncoder

It produces much higher quality JPEGs than the .Net built-in, but still is not as good as Gimp’s or Photoshop’s. Filesizes also tend to be larger.

BitMiracle’s implementation is practically identical to the .Net built-in – same quality problems.

It’s likely that just wrapping an existing open source implementation, like Google’s jpeg_optimizer in PageSpeed Tools – seemingly libjpeg underneath, would be the most efficient option.

Update

ArpanJpegEncoder appears to have issues once it’s deployed – maybe I need to increase the trust level of the code, or perhaps something else is going on. Locally it writes images fine, but once deployed I get a blank black image from it every time. I’ll update if I determine the cause. Just a warning to others considering it.

Leave a Comment