mercredi 2 septembre 2015

ASP MVC can't display image in view

So I've got this image in the shape of a byte[] that I want to display in my view.

This is my model of the image:

    public class SlideModel
    {
        public Byte[] imageFirst { get; set; }
    }

This is my controller picking out the image from a db:

public ActionResult Slide()
    {
        string cs = "Data Source=" + Environment.CurrentDirectory + "\\ImageDB.db";

        using (SQLiteConnection con = new SQLiteConnection(cs))
        {
            var listOfImages = new List<ImageModel>();
            string stm = "SELECT * FROM Image";
            con.Open();

            using (SQLiteCommand cmd = new SQLiteCommand(stm, con))
            {
                using (SQLiteDataReader rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        listOfSlides.Add(new SlideModel
                        {
                            imageFirst = Serialize(rdr["image_first"]),
                        });
                    }

                    rdr.Close();
                    Images = listOfImages;
                }
            }

            con.Close();
        }
        return View(Images);
    }

    public static byte[] Serialize(object obj)
    {
        var binaryFormatter = new BinaryFormatter();
        var ms = new MemoryStream();
        binaryFormatter.Serialize(ms, obj);
        return ms.ToArray();
    }

And this is when I try to show the image in the view:

<img src="data:image/jpg;base64,@(Convert.ToBase64String(@item.imageFirst))" width="300px"/>

But all I get is this icon: View image fail

I can't for the love of me figure out why it can't be shown. The images are stored as what I can only assume is a blob in the database, but right now I wish they were just image files on the disc, as that seems to make it a lot easier to attach them to the view.

Aucun commentaire:

Enregistrer un commentaire