John Lam 1997 — 2026

Resizing JPEG images using System.Imaging

I needed to resize an image on my laptop today, and realized that I didn’t have Photoshop installed since my last repave. So I just whipped up a simple little C# class that will do the dirty work. The nice feature of this class is the ability to specify the image quality of the saved JPEG image. Enjoy!

public sealed class Resizer
{
  private Bitmap bitmap_;
  private Bitmap result_;

  private Resizer(string path)
  {
    bitmap_ = new Bitmap(path, true);
  }

  private ImageCodecInfo GetEncoder(string mimeType)
  {
    ImageCodecInfo[] encoders = ImageCodecInfo.GetImageDecoders();

    for (int i = 0; i < encoders.Length; ++i)
      if (encoders[i].MimeType == mimeType)
        return encoders[i];

    return null;
  }

  public static Resizer CreateFromPath(string path)
  {
    return new Resizer(path);
  }

  public Bitmap Bitmap
  {
    get { return bitmap_; }
  }

  public void Resize(Size size)
  {
    if (result_ != null)
      result_.Dispose();

    result_ = new Bitmap(bitmap_, size);
    using (Graphics g = Graphics.FromImage(result_))
    {
      g.SmoothingMode = SmoothingMode.HighQuality;
      g.DrawImage(result_, 0, 0, size.Width, size.Height);
    }
  }

  public void Resize(Size size, string path, int quality)
  {
    Resize(size);
    Save(path, quality);
  }

  public void Save(string path, int quality)
  {
    if(result_ == null)
      throw new Exception("You must resize the bitmap before you save it.");

    ImageCodecInfo ci = GetEncoder("image/jpeg");
    if(ci == null)
      throw new Exception("Failed to get JPEG image encoder.");

    EncoderParameters parameters = new EncoderParameters(1);
    parameters.Param[0] = new EncoderParameter(Encoder.Quality, (long)quality);
    result_.Save(path, ci, parameters);
  }
}
1 archived reader comment

Corey Henderson (2004-02-06)

http://www.microsoft.com/windowsxp/pro/downloads/powertoys.asp — go with “Image Resizer” from XP Powertoys, right click resize gives you 3 options for small,medium, large.