0

Having an issue where my images appear as errors. Tried both methods of converting a byte array to an image. Any help is appreciated.

View:

        if (product.ImageUploadBytes != null)
        {
            var base64 = Convert.ToBase64String(product.ImageUploadBytes);
            var imgSrc = String.Format("data:image/gif;base64,{0}", base64);

            <div class="panel-body"><img src=@imgSrc /></div>
            <img src="@Url.Action("GetImage", "Products", new { id = product.ID })" />
        }

Controller:

    public ActionResult GetImage(int imageID)
    {
        Product p = new Product();
        p = _context.Products.FirstOrDefault(x => x.ID == imageID);

        if (p.ImageUploadBytes != null)
        {
            return File(p.ImageUploadBytes, "image/png");
        }
        else
        {
            return null;
        }
    }

Byte Array in DB: Image

Image Uploading to DB:

    [HttpPost]
    public ActionResult AddImage(Product model, HttpPostedFileBase image)
    {
        if (image != null)
        {
            model.ImageUploadBytes = new byte[image.ContentLength];
            image.InputStream.Read(model.ImageUploadBytes, 0, image.ContentLength);
        }
        _context.Products.Add(model);
        _context.SaveChanges();


        return View(model);
    }
dan213
  • 1
  • 1
  • Updated, thanks for explaining that – dan213 Apr 19 '18 at 02:07
  • what's the mime type for the image you are trying to show. in your first block of code you are trying to show a gif, in the second a png both hardcoded. Are you storing the extension or mime type when you store the image so that you can create the correct img tag? – Fran Apr 19 '18 at 02:11
  • @Fran Image is a .png, that could be the issue let me update the post with how the image is stored. – dan213 Apr 19 '18 at 02:14
  • Could you please have a look at my answer on **[How to display images in MVC](https://stackoverflow.com/questions/30651531/how-to-display-images-in-mvc/30653266#30653266)**? – Murat Yıldız Apr 19 '18 at 12:59
  • Figured it out, needed an [AllowAnonymous] tag on the GetImage action. Thanks for the posts – dan213 Apr 20 '18 at 04:33

0 Answers0