6

I am storing images in Database as Binary Images successfully. I want to display these images in Edit form to modify and save changes. System.OutOfMemoryException' was thrown in Edit.cshtml form while displaying Binary Images from Database.

Can someone please correct my code.

Model class:

public class Accommodation
    {
        [Key]
        public string A_Unique_Id { get; set; }

        public byte[] Picture1 { get; set; }

        public byte[] Picture2 { get; set; }

        public byte[] Picture3 { get; set; }


  }

// GET: /Accommodation/Edit/5

public ActionResult Edit(string id)
    {
        Accommodation accommodation = db.Accommodation.Find(id);
        ViewBag.SelectedAustraliaStateId = new SelectList(db.AustraliaStates, "AustraliaStateId", "AustraliaStateName", accommodation.SelectedAustraliaStateId);

        return View(accommodation);
    }

// POST: /Accommodation/Edit/5

[HttpPost]
public ActionResult Edit(Accommodation accommodation)
{
    if (ModelState.IsValid)
    {
        db.Entry(accommodation).State = EntityState.Modified;

        //the following line is for re-assigning back the DDL modified value.
        accommodation.State = accommodation.SelectedAustraliaStateId;

        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(accommodation);
}

Edit.cshtml

<div class="editor-label">
        @Html.LabelFor(model => model.Picture1)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Picture1)
        @Html.ValidationMessageFor(model => model.Picture1)
    </div>

ERROR MESSAGE: Exception of type 'System.OutOfMemoryException' was thrown at line @Html.EditorFor(model => model.Picture1)

Reddy
  • 97
  • 1
  • 3
  • 10

2 Answers2

18

To display image in your view

View

<form  method="post" enctype="multipart/form-data">
@{
    if (Model.Picture1 != null)
      {
         string imageBase64 = Convert.ToBase64String(Model.Picture1);
         string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
         <img src="@imageSrc" width="100" height="100" />
      }
  }
    <input type="file" name="photo" id="files" accept="image/*;capture=camera">
    <button type="button">Submit</button>
  </form>

Controller

[HttpPost]
public ActionResult Edit(Accommodation accommodation)
{

  if (Request.Files["files"] != null)
    {
            byte[] Image;
            using (var binaryReader = new BinaryReader(Request.Files["files"].InputStream))
            {
                Image = binaryReader.ReadBytes(Request.Files["files"].ContentLength);
            }
    }
    accommodation.Picture1=Image;
  //your code to save data
}
Nilesh Gajare
  • 6,302
  • 3
  • 42
  • 73
  • Hi Nilesh, this code is only to display the Image in edit view but when I submit the modified form, it is saving as NULL in Picture1 field. how can I save the image as well? – Reddy Jan 29 '14 at 04:37
  • @Reddy are you getting the Image in your controller – Nilesh Gajare Jan 29 '14 at 04:43
  • both GET and POST controllers are in the above code. Can you please check it. – Reddy Jan 29 '14 at 04:44
  • Getting an error message as "system.drawing.image' is a 'type' but is used like a 'variable'" at line Image = binaryReader.ReadBytes(Request.Files["files"].ContentLength); – Reddy Jan 29 '14 at 22:07
  • Nilesh, can you please let me know how to fix it. Thanks – Reddy Jan 29 '14 at 22:16
  • @Reddy image is not `system.drawing.image` object it is simply a variable check edited answer – Nilesh Gajare Jan 30 '14 at 04:02
  • HI Nilesh, thanks for correction. It is still inserting NULL values in the images fields after edit and save. "files" is not coming from database right? I need to retrieve the existing binary image from Database and update the same image instead of adding as NULL – Reddy Jan 30 '14 at 04:18
  • @Reddy yes during edit you have to check if image is not present then dont update else update the field in db – Nilesh Gajare Jan 30 '14 at 04:34
  • I am not a experienced developer but trying to implement a small solution. Can you please let me know where do I have check if image is not present then dont update else update the field in db – Reddy Jan 30 '14 at 04:51
  • @Nilesh its not work for me accommodation use byte[] but sended values are httppostedfilebase , i think i should create custom ByteArrayModelBinder – AminM Jun 15 '18 at 08:42
  • @AminM can you share your code to get more clarification – Nilesh Gajare Jun 15 '18 at 09:16
  • @Nilesh my code is similar but after click edit and choose new image it sended back to actionmethod as HttpPostedFileBase but beacuse model is byte array it throw 'mvc upload image The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters' here is my code https://dotnetfiddle.net/v1FnN9 – AminM Jun 15 '18 at 13:58
0
byte[] imageByteData = System.IO.File.ReadAllBytes(imageFile);

string imageBase64Data = Convert.ToBase64String(imageByteData);

string imageDataURL = string.Format("data:image/jpg;base64{0}",imageBase64Data);

Session["photo"] = imageDataURL;

In _layout.cshtml page add this line.

Ghasem
  • 14,455
  • 21
  • 138
  • 171