Search code examples
c#gdi+system.drawing

A generic error occured in GDI+ while saving image


I have to save an image in post request in byte64String format when i save that image i get A generic error occurred in GDI+

here is my code

byte[] ix = Convert.FromBase64String(obj.Image);

var ID = obj.Id;

using (var mStream = new MemoryStream(ix))
{
var img = Image.FromStream(mStream);

var image = obj.ImageName + ".jpg";
string path = HostingEnvironment.MapPath("/Images/" + ImageType + "/" + ID + "/" + image);
System.IO.Directory.CreateDirectory(path);


try
{
   img.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);

}
catch (Exception e)
{
var d = e;
}
}

also this is not a permission issue as i am able to create text files in the same directory


Solution

  • Quite simply you are confusing paths and filenames.

    The problem if could hazzard a guess, you probably have a folder that is your filename, and you are trying to save a file with that same name, which windows forbids

    Your code tweaked

    var image = $"{obj.ImageName }.jpg";
    
    // get the path, and only the path
    string path = HostingEnvironment.MapPath($"/Images/{ImageType}/{ID}/");
    
    // Create directory if needed (from that path)
    Directory.CreateDirectory(path,image);
    
    ...
    
    // now create the correct full path    
    var fullPath = Path.Combine(path,fileName);
    
    // save
    img.Save(fullPath, ImageFormat.Jpeg);