title: Generating image thumbnails in ASP.NET?
body: <p>What is the fastest and more reliable way of generating thumbnails in .NET? I need to get any image, compress it in JPEG and resize it.</p>
  
  <p>I've seen several examples with GDI+, some non-free components and I remember WPF has some good stuff about imaging. GDI+ is pretty old and the WPF stuff maybe has no benefits on a server environment though.</p>
  
  <p>This has to work in a ASP.NET MVC application that runs on full trust, and if possible, synchronously.</p>
  
  <p>What would you recommend? </p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Based on <a href="https://stackoverflow.com/questions/5882307/generating-image-thumbnails-in-asp-net/5882623#5882623">Mantorok's answer</a> I have worked out this example, but it's still GDI+, and it crashes if I try with a large image:</p>
  
  <pre><code>public void GenerateThumbnail(String filename, Int32? desiredWidth, 
      Int32? desiredHeight, Int64 quality, Stream s)
  {
      using (Image image = Image.FromFile(filename))
      {
          Int32 width=0, height=0;
  
          if ((!desiredHeight.HasValue &amp;&amp; !desiredWidth.HasValue) ||
              (desiredHeight.HasValue &amp;&amp; desiredWidth.HasValue))
              throw new ArgumentException(
                  "You have to specify a desired width OR a desired height");
  
          if (desiredHeight.HasValue)
          {
              width = (desiredHeight.Value * image.Width) / image.Height;
              height = desiredHeight.Value;
          }
          else
          {
              height = (desiredWidth.Value * image.Height) / image.Width;
              width = desiredWidth.Value;
          }
  
          using (var newImage = new Bitmap(width, height))
          using (var graphics = Graphics.FromImage(newImage))
          using (EncoderParameter qualityParam = 
              new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 
                  quality))
          using (EncoderParameters encoderParams = new EncoderParameters(1))
          {
              graphics.DrawImage(image, 0, 0, width, height);
              ImageCodecInfo jpegCodec = ImageCodecInfo.GetImageEncoders().
                  Single(e =&gt; e.MimeType.Equals("image/jpeg", 
                      StringComparison.Ordinal));
              encoderParams.Param[0] = qualityParam;
              newImage.Save(s, jpegCodec, encoderParams);
          }
      }
  }
  </code></pre>