调整图像gdi + graphics .net的大小

我有这种方法缩小我正在处理的网站的图像:

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 > img.Height) { if (img.Width <= 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 <= 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; } 

大部分时间它工作得很好,但有时它给了我这个例外:GDI +中发生了一般错误。 错误代码-2147467259。 资料来源:“System.Drawing”。 这发生在Image.Save上(…我试图使这段代码尽可能防御,但仍然没有得到什么导致这种情况。如果有人知道答案那么好,那么批评也是受欢迎的。

查看Image.FromStream()的文档

http://sofzh.miximages.com/c%23/) { using (MemoryStream thumbData = new MemoryStream()) { int newWidth; int newHeight; if ((original.Width = newMaxWidth) (original.Height = newMaxHeight)) { original.Save(thumbData, ImageFormat.Jpeg); return thumbData.ToArray(); } if (original.Width > original.Height) { newWidth = newMaxWidth; newHeight = (int)(((float)newWidth / (float)original.Width) * (float)original.Height); } else { newHeight = newMaxHeight; newWidth = (int)(((float)newHeight / (float)original.Height) * (float)original.Width); } //original.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero) // .Save(thumbData, ImageFormat.Jpeg); //return thumbData.ToArray(); using (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(original, 0f, 0f, (float)newWidth, (float)newHeight); thumb.Save(thumbData, ImageFormat.Jpeg); } } }