1

I am storing images as byte arrays inside a SQL database.

Here is my Index method (inside the controller):

public ActionResult Index()
{
    var list = db.UserProfiles.ToList();

    Dictionary<int, ActionResult> picture = list.ToDictionary(item => item.CarID, item => CarPic(item.Picture));

    ViewBag.CarPictures = picture;

    return View(list);
}

Here is my CarPic method:

public ActionResult CarPic(byte[] imageBytes)
{
    return imageBytes == null ? null : File(imageBytes, "image/jpeg");
}

Here is how I am trying to display the image inside my view:

foreach(var item in Model)
{
    <img src="@ViewBag.CarPictures[item.CarID]"/>
}

This is what shows up in the web browser:

Image

Here is a screenshot of Intellisense:

Intellisense

So Picture is not null, it is a byte array. The image itself is a JPEG. Here is the code I am using to convert the image to a byte array to store it in the database:

[Authorize]
[HttpPost]
public ActionResult Create(Stock stock, HttpPostedFileBase file)
{
    if (file != null)
    {
        if (file.ContentType.Contains("image"))
        {
            using (var inputStream = file.InputStream)
            {
                var memoryStream = inputStream as MemoryStream;
                if (memoryStream == null)
                {
                    memoryStream = new MemoryStream();
                    inputStream.CopyTo(memoryStream);
                }

                var data = memoryStream.ToArray();

                stock.Picture = data;
            }
        }
    }

    if (ModelState.IsValid)
    {
        db.UserProfiles.Add(stock);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(stock);
}

I have checked the Database and the field is indeed populated. Here is my Stock model:

[Table("Stock")]
public class Stock
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int CarID { get; set; }

    public byte[] Picture { get; set; }
    //etc etc
}

I am tearing my hair out here trying to work out why this isn't working, as I think I have done everything right. What am I doing wrong?

Thanks very much

4

1 回答 1

3

You're misunderstanding the <img> tag.

<img src="..." /> allows you to display an image from a URL.
The src attribute must specify a URL that returns the actual image.

If you want to embed the image in the page, you can use a data: URI.

于 2013-02-10T17:15:09.077 回答