title: Resize image gdi+ graphics .net
body: <p>I have this method for shrinking down an image for a website that I'm working on:</p>
  
  <pre><code>static byte[] createSmallerImage(
     BlogPhoto blogPhoto, 
     int newMaxWidth, 
     int newMaxHeight)
  {
    Image img;
    using (MemoryStream originalImage = 
             new MemoryStream(blogPhoto.BlogPhotoImage))
    {
      img = Image.FromStream(originalImage);
    }
  
    int newWidth;
    int newHeight;
    byte[] arr;
  
    if (img.Width &gt; img.Height)
    {
      if (img.Width &lt;= newMaxWidth)
      {
  
        using (MemoryStream thumbStr = new MemoryStream())
        {
          img.Save(thumbStr, ImageFormat.Jpeg);
          img.Dispose();
          arr = thumbStr.ToArray();
        }
        return arr;
      }
  
      newWidth = newMaxWidth;
      newHeight = 
         (int)(((float)newWidth / (float)img.Width) * (float)img.Height);
    }
    else
    {
      if (img.Height &lt;= newMaxHeight)
      {
  
        using (MemoryStream thumbStr = new MemoryStream())
        {
          img.Save(thumbStr, ImageFormat.Jpeg);
          img.Dispose();
          arr = thumbStr.ToArray();
        }
        return arr;
      }
  
      newHeight = newMaxHeight;
      newWidth = 
        (int)(((float)newHeight / (float)img.Height) * (float)img.Width);
    }
  
    Image thumb = new Bitmap(newWidth, newHeight);
  
    Graphics g = Graphics.FromImage(thumb);
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    g.SmoothingMode = SmoothingMode.HighQuality;
    g.PixelOffsetMode = PixelOffsetMode.HighQuality;
    g.CompositingQuality = CompositingQuality.HighQuality;
  
    g.DrawImage(img, 0f, 0f, (float)newWidth, (float)newHeight);
  
  
    using (MemoryStream thumbStr = new MemoryStream())
    {
      thumb.Save(thumbStr, ImageFormat.Jpeg);
      arr = thumbStr.ToArray();
    }
  
    g.Dispose();
    img.Dispose();
  
    return arr;
  }
  </code></pre>
  
  <p>Most of the time it works great but sometimes it gives me this exception:A generic error occurred in GDI+. Error Code -2147467259. Source: "System.Drawing".  This occurs on the Image.Save(... I tried to make this code as defensive as possible but am still not getting whats causing this.  If someone knows the answer that'd be great, critiques are welcome too.</p>