views:

38

answers:

0

I get the exception "A generic error occurred in GDI+" when calling destImage.Save() at the end of this function. This resizes an image uploaded to my ASP.NET app:

public static void ResizeImageFile(string sourceFileName, string destinationFileName, int width, int height)
    {
      using (var sourceImage = Image.FromFile(sourceFileName))
      {
        using (var destImage = ResizeImage(sourceImage, width, height))
        {
          var jpgEncoder = GetEncoder(ImageFormat.Jpeg);
          var qualityParam = new EncoderParameter(Encoder.Quality, 50L);
          var encoderParams = new EncoderParameters(1);
          encoderParams.Param[0] = qualityParam;

          destImage.Save(destinationFileName, jpgEncoder, encoderParams);
        }
      }
    }

public static Image ResizeImage(Image sourceImage, int width, int height)
    {
      var destX = 0;
      var destY = 0;

      float nPercent;

      var sourceWidth = sourceImage.Width;
      var sourceHeight = sourceImage.Height;

      var nPercentW = (width / (float)sourceWidth);
      var nPercentH = (height / (float)sourceHeight);

      if (nPercentH < nPercentW)
      {
        nPercent = nPercentW;
        destY = (int)((height - (sourceHeight * nPercent)) / 2);
      }
      else
      {
        nPercent = nPercentH;
        destX = (int)((width - (sourceWidth * nPercent)) / 2);
      }

      var destWidth = (int)(sourceWidth * nPercent);
      var destHeight = (int)(sourceHeight * nPercent);

      var bmPhoto = new Bitmap(width, height, PixelFormat.Format16bppRgb555);
      bmPhoto.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);

      using (var grPhoto = Graphics.FromImage(bmPhoto))
      {
        grPhoto.SmoothingMode = SmoothingMode.HighQuality;
        grPhoto.CompositingQuality = CompositingQuality.HighQuality;
        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
        grPhoto.DrawImage(sourceImage, new Rectangle(destX, destY, destWidth, destHeight),
                          new Rectangle(0, 0, sourceWidth, sourceHeight), GraphicsUnit.Pixel);
      }

      return bmPhoto;
    }

There isn't any more useful info, and it doesn't happen with every image. Any idea as to how I may further diagnose this?

Thanks, Mark