代码之家  ›  专栏  ›  技术社区  ›  Majid Dehnamaki

将varbinary转换为img并在mvc4中显示图像

  •  0
  • Majid Dehnamaki  · 技术社区  · 11 年前

    我为在数据库中保存图像编写了以下代码:

    public ActionResult Create(Slider slider)
        {
            if (ModelState.IsValid)
            {
                int Len = Request.Files[0].ContentLength;
                byte[] fileBytes = new byte[Len];
                Request.Files[0].InputStream.Read(fileBytes, 0, Len);
                slider.SliderImage = fileBytes;
                db.Slider.Add(slider);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
    
            return View(slider);
        }
    

    如何将varbinary更改为image以显示数据?

    2 回复  |  直到 11 年前
        1
  •  1
  •   serene    11 年前

    将字节数组转换为base64字符串并显示如下 将字节数组转换为64进制字符串的代码

     public static string ToBase64ImageString(this byte[] data)
            {
                return string.Format("data:image/jpeg;base64,{0}", Convert.ToBase64String(data));
            }
    

    要将其显示为图像,可以使用以下代码

    <img src='@Model.SliderImage.ToBase64ImageString()' />
    

    不要忘记在视图中使用扩展方法的名称空间。

        2
  •  0
  •   Kartikeya Khosla    11 年前

    就我所理解的问题而言,为了在asp.net中显示图像,mvc以下代码将起作用:-

     public ActionResult DownloadFile(int fileId)
     {
       SliderEntities db = new SliderEntities ();
    
       var content = db.Slider.Where(m => m.ID == fileId).FirstOrDefault();
    
       byte[] contents = (byte[])content.SliderImage;  //here varbinary to byte conversion will take place.
    
       return File(contents, "image/jpg");  //here instead of 'jpg' you can return any image format. 
    }