A generic error occurred in GDI+

1.9k Views Asked by At

A have an image upload function that works fine on localhost but when I try and run under Windows Server 2003 I get the error message

This is the code..

Now before anyone jumps on me ;) I've looked at the previous answers and I've checked all permissions and they seem to be correct.. the folder/paths exist, etc..

ImageService imageService = new ImageService();

if (fileBase != null && fileBase.ContentLength > 0 && fileBase.ContentLength <= 2097152 && fileBase.ContentType.Contains("image/"))
{
    var uploadedPath = "~/Assets/Images/";

    Path.GetExtension(fileBase.ContentType);
    var extension = Path.GetExtension(fileBase.FileName);

    if (extension.ToLower() != ".jpg" && extension.ToLower() != ".gif") // only allow these types
    {
        photoViewModel.ImageValid = "Not Valid";
        ModelState.AddModelError("Photo", "Wrong Image Type");
        return View(photoViewModel);
    }

    EncoderParameters encodingParameters = new EncoderParameters(1);
    encodingParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);

    ImageCodecInfo jpgEncoder = imageService.GetEncoderInfo("image/jpeg");
    var uploadedimage = Image.FromStream(fileBase.InputStream, true, true);

    Bitmap originalImage = new Bitmap(uploadedimage);
    Bitmap newImage = new Bitmap(originalImage, 274, 354);

    Graphics g = Graphics.FromImage(newImage);
    g.InterpolationMode = InterpolationMode.HighQualityBilinear;
    g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);

    var streamLarge = new MemoryStream();
    newImage.Save(streamLarge, jpgEncoder, encodingParameters);

    var fileExtension = Path.GetExtension(extension);
    string newname;
    if (photoViewModel.photoURL != null)
    { newname = photoViewModel.photoURL; }
    else
    { newname = Guid.NewGuid() + fileExtension; }

    var ImageName = newname;
    newImage.Save(Server.MapPath(uploadedPath) + ImageName);
    System.IO.File.WriteAllBytes(Server.MapPath(uploadedPath) + ImageName, streamLarge.ToArray());

    photoViewModel.uploadedPath = uploadedPath;
    photoViewModel.photoURL = ImageName;

    originalImage.Dispose();
    newImage.Dispose();
    streamLarge.Dispose();
    return View(photoViewModel);
}
1

There are 1 best solutions below

1
On BEST ANSWER

With Image.FromStream, the stream must remain open for the lifetime of the image. That means if the stream is a file, the file will be held open. I think you'll need to dispose uploadedImage to allow the stream to be closed (if you wait for the GC to clean up the uploadedImage, this will occur at an indeterminate point in the future - or may not occur at all).