简体   繁体   中英

Error converting byte array to Image

I've read images in and saved them in a database in byte[] format. Later I want to retrieve the images and convert them into Image format. I've written the following method:

private List<Image> ConvertByteArraysToImages(List<byte[]> byteDataList)
{
    List<Image> retVal = new List<Image>();

    int counter = 0;
    foreach (byte[] byteData in byteDataList)
    {
        // Something is wrong here
        MemoryStream memstr = new MemoryStream(byteData);
        Image img = Image.FromStream(memstr);
        retVal.Add(img);
        memstr.Dispose();// Just added this
        // This works fine, the images appear in the folder
        System.IO.File.WriteAllBytes(String.Format(@"C:\dev\test{0}.png", counter), byteData);
        counter++;
    }

    return retVal;
}

I'm calling this method from an action which adds the images to the ViewBag to use in the view.

public ActionResult ViewTicket(Incident ticket)
{
    //Read the ticket via the web API
    string serialisedJSON = JsonConvert.SerializeObject(ticket.ID);
    string response = TicketUtilities.JSONRequestToAPI(serialisedJSON, "GetSingleIncident");
    Incident retVal = JsonConvert.DeserializeObject<Incident>(response);
    //Convert byte[] to Image and add to ViewBag
    List<Image> ScreenshotImagesFullsize = ConvertByteArraysToImages(retVal.Screenshots);
    ViewBag.Add(ScreenshotImagesFullsize); //Error here
    return View(retVal);
}

When I try to add the images to the ViewBag I get the following error in the browser:

Cannot perform runtime binding on a null reference 

Writing the byte arrays to file produces the correct output but I'm not getting a list of Images in my return value. Hovering over retVal in debug mode shows the following:

在此处输入图片说明

I passed in two byte arrays and I see 2 objects in retVal , but I also I see the error: "Cannot evaluate expression because the code of the current method is optimized". Why does this occur?

Update: I disabled JIT optimization and now I can see the following:

在此处输入图片说明

I can see that the object has correctly acquired properties such as the height and width but the actual data is null.

Do not dispose the stream and do keep at least one reference to it as long as you need the image.

"You must keep the stream open for the lifetime of the Image."

https://msdn.microsoft.com/de-de/library/1kcb3wy4(v=vs.110).aspx

Note that there is no need to manually call dispose on a MemoryStream because it does not have unmanaged resources

So I solved this, the problem turned out not to be the conversion but rather adding Image objects to the view. For some reason adding Image objects to the view does not work, to overcome this I converted the image to a Base64 string

        using (MemoryStream m = new MemoryStream())
        {
            retVal.Img.Save(m, retVal.Img.RawFormat);
            byte[] imageBytes = m.ToArray();

            // Convert byte[] to Base64 String
            string imreBase64Data = Convert.ToBase64String(imageBytes);
            retVal.ImgB64 = string.Format("data:image/png;base64,{0}", imreBase64Data);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM