通过API控制器在Angular JS中显示字节阵列中的图像



我有一个服务器端为ASP.NET的应用程序。我想显示应用程序中API控制器在ِ数据库上存储的图像。这是一个Angular JS应用。在服务器端,图像存储在数据库中,如下所示:

[HttpPost]
public ActionResult Create(House house,HttpPostedFileBase Photon)
{
    if (ModelState.IsValid)
    {
        house.Id = Guid.NewGuid();
        if (Photon != null && Photon.ContentType.StartsWith("image"))
        {
            mImage img = new mImage
            {
                Photo = new byte[Photon.ContentLength],
                PhotoType = Photon.ContentType,
                photoName = Photon.FileName,
                HouseId = house.Id
            };
            Photon.InputStream.Read(img.Photo, 0, Photon.ContentLength);
            db.mImages.Add(img);
        }
        var area = db.Areas.Find(house.AreaId);
        house.visit = 0;
        db.Houses.Add(house);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    ViewBag.AreaId = new SelectList(db.Areas, "Id", "name", house.AreaId);
    return View(house);
}

并以这种方式显示。

[AllowAnonymous]
public ActionResult ShowPhoto(Guid id)
{
    using (var db = new myDB())
    {
        var p = db.mImages.Find(id);
        System.IO.MemoryStream myMemStream = new System.IO.MemoryStream(p.Photo);
        System.Drawing.Image fullsizeImage = System.Drawing.Image.FromStream(myMemStream);
        System.Drawing.Image newImage = fullsizeImage.GetThumbnailImage(150, 150, null, IntPtr.Zero);
        System.IO.MemoryStream myResult = new System.IO.MemoryStream();
        newImage.Save(myResult, System.Drawing.Imaging.ImageFormat.Jpeg);  //Or whatever format you want.
        return File(myResult.ToArray(), "image/Jpeg");
    }
}

如何使用此方法在API控制器中显示图像?

根据OP上的注释在此处发布解决方案。解决方案是将字节数组序列化为JSON,并将其作为JsonResult返回到以下效果;

的效果;
[AllowAnonymous]
public ActionResult ShowPhoto(Guid id)
{
    using (var db = new myDB())
    {
        var p = db.mImages.Find(id);
        System.IO.MemoryStream myMemStream = new System.IO.MemoryStream(p.Photo);
        System.Drawing.Image fullsizeImage = System.Drawing.Image.FromStream(myMemStream);
        System.Drawing.Image newImage = fullsizeImage.GetThumbnailImage(150, 150, null, IntPtr.Zero);
        System.IO.MemoryStream myResult = new System.IO.MemoryStream();
        newImage.Save(myResult, System.Drawing.Imaging.ImageFormat.Jpeg);      //Or whatever format you want.
        return Json(new { myResult.ToArray() });
    }
}

最新更新