我有一个服务器端为asp.net的应用程序。我想通过应用程序中的api控制器在数据库中显示存储为字节数组的图像。这是一个角度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控制器中显示图像?
答案 0 :(得分:0)
根据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() });
}
}