1

I'm trying to save a file in specified format, inside an mvc controller, by passing the file 'InputStream' to the Bitmap object, and save the bitmap, instead of save the file itself... as i want to process it.

for first step, i tried writing as what as i said, and pas a png, and then a jpg file i found on my pc, but i receive the following error:

A generic error occurred in GDI+.

My code are as following:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,HotelId")] Image image) //, HttpPostedFileBase file)
{
    int arrayStartX;

    if (ModelState.IsValid)
    {
        if (Request.Files.Count > 0)
        {
            var file = Request.Files[0];

            if (file != null && file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var pathMain = Path.Combine(Server.MapPath("~/Images/HotelGallery/"),
                    "Img" + image.HotelId + "_" + fileName.Remove(fileName.LastIndexOf('.')) + ".jpg");
                //file.SaveAs(path);

                try
                {
                    file.InputStream.Seek(0, SeekOrigin.Begin);
                    Bitmap mainBmp = new Bitmap(file.InputStream);
                    mainBmp.Save(pathMain, ImageFormat.Jpeg);
Hassan Faghihi
  • 1,888
  • 1
  • 37
  • 55

2 Answers2

2

Well though it was rough for me to get GDI+ error, facing it a lot in the past, i never come with idea that there maybe somethings goes wrong with my own file system. yes, though i always look at the GDI+ as the demon this time it were wholly my own fault, ( BTW, microsoft should provide better error :@ ) The Issue were that i didn't generated directory, and the Save were not able to do it either.

So i done a little refactoring and done this:

var fileName = Path.GetFileName(file.FileName);
var galleryDirectoryPath = Server.MapPath("~/Images/HotelGallery/");
var pathMain = Path.Combine(galleryDirectoryPath,
               "Img" + image.HotelId + "_" + fileName.Remove(fileName.LastIndexOf('.')) + ".jpg");

if (!Directory.Exists(galleryDirectoryPath))
{
    Directory.CreateDirectory(galleryDirectoryPath);
}

then the rest of code.

Hassan Faghihi
  • 1,888
  • 1
  • 37
  • 55
0

You can try your stream code like below:

// At this point the new bitmap has no MimeType
// Need to output to memory stream

    using (var m = new MemoryStream())
    {
           dst.Save(m, format);

           var img = Image.FromStream(m);

           //TEST
           img.Save("C:\\test.jpg");
           var bytes = PhotoEditor.ConvertImageToByteArray(img);


           return img;
     }

source : A generic error occurred in GDI+, JPEG Image to MemoryStream

Community
  • 1
  • 1
Sunil Kumar
  • 3,142
  • 1
  • 19
  • 33
  • what is format? i think it used with Serialize format, when using file system as source...and what is dst? none the stream, nor the HttpRequestBase (Request.Files) have the Save – Hassan Faghihi Oct 08 '16 at 05:54