2017-09-12 34 views
2

我有一個其服務器端爲asp.net的應用程序。我想在應用程序中通過api控制器在Database上顯示以字節數組形式存儲的圖像。這是一個角度js應用程序。 在服務器端,將圖像存儲在數據庫中,如下所示:通過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

我錯過了什麼,或者你可以不只是引用是像'img'標籤中的URL那樣; ''(用實際的guid替換)? – DiskJunky

+0

我做這個工作,我的asp.net mvc的控制器,但我想通過API控制器顯示在科爾多瓦應用圖片,我怎麼能使用保存在數據庫中的圖像,它們保存喜歡的字節數組 – marjaan

+0

既然如此,如果你」重新使用WebApi來返回字節數組,然後讓你的方法返回類型爲'byte []'。如果你從一個正常的控制器服務這個,那麼你就需要序列化的字節數組(通常作爲JSON)並返回一個'JsonResult'。或者我誤解了這個要求? – DiskJunky

回答

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() }); 
    } 
}