2016-10-05 95 views

回答

0

要動態加載圖像,我創建了一個名爲的新類/模型ImageModel

public class ImageModel 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Description { get; set; }  
    public Byte[] ImageBytes { get; set; } 
} 

這類有一個叫做圖片場,它會加載圖像。 下一步是將ImageBytes字段添加到報告中。

通過Crystal Report接口,使用字段資源管理器,它創建一個新的連接。在這個新的連接中,我用我的ImageModel類作爲模型。 通過添加ImageBytes字段,我注意到Crystal Reports增加了一個類型crBlobFieldObject對象。

要加載的圖像是必要做出如下代碼:

public Byte[] GetImageBytes(string image_name) 
{ 
    Byte[] bytes = null; 
    if (!string.IsNullOrEmpty(image_name)) 
    { 
     string app_path = ((System.Web.HttpRequestWrapper)this.Request) 
           .PhysicalApplicationPath; 
     app_path += "Content\\images\\"; 
     string full_path = app_path + image_name; 
     // 
     if (System.IO.File.Exists(full_path)) 
     { 
      FileStream fs = new FileStream(full_path, FileMode.Open, FileAccess.Read); 
      BinaryReader br = new BinaryReader(fs); 
      bytes = br.ReadBytes(Convert.ToInt32(br.BaseStream.Length)); 
     } 
    } 
    return bytes; 
} 

主要的代碼如下所示:

public JsonResult GenerateCrystalReportImage() 
{ 
    List<ImageModel> list_image = new List<ImageModel>(); 
    // 
    ImageModel imageone = new ImageModel(); 
    imageone.Id = 1; 
    imageone.Name = "Image name one"; 
    imageone.Description = "This is a image description one"; 
    imageone.Image = GetImageBytes("imageone.png"); 
    list_image.Add(imageone); 
    // 
    ImageModel imagetwo = new ImageModel(); 
    imagetwo.Id = 2; 
    imagetwo.Name = "Image name two"; 
    imagetwo.Description = "This is a image description two"; 
    imagetwo.Image = GetImageBytes("imagetwo.png"); 
    list_image.Add(imagetwo); 
    // 
    ReportDocument rp = new ReportDocument(); 
    rp.Load(System.Web.HttpContext.Current.Server.MapPath("~/Reports/") + "Test.rpt"); 
    rp.SetDataSource(list_image); 
    rp.ExportToHttpResponse(ExportFormatType.PortableDocFormat, 
          System.Web.HttpContext.Current.Response, 
          false, 
          "image_list_" + DateTime.Now); 
    rp.Close(); 
    return Json(new 
    { 
     data = "ok", 
     results = 1, 
     success = true, 
     errors = String.Empty 
    }, JsonRequestBehavior.AllowGet); 
}