aneuk aneuk - 10 days ago 4x
ASP.NET (C#) Question

Crystal Report load image (bytes[]) at runtime with C#

I have a report where there is a static image, but I need to load the image dynamically.

Already checked this, this, this and this

All I tried without success. I need some sample code.

Any suggestion?


To load images dynamically I created a new class/model called ImageModel.

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

This class has a field called Image, it will load the image. The next step is add ImageBytes field to the report.

Through Crystal Report interface, using the Field Explorer, it was to create a new connection. In this new connection I used my ImageModel class as a model. By adding the ImageBytes field, I noticed that Crystal Reports added a type crBlobFieldObject object.

To load the image was necessary to make the following code:

public Byte[] GetImageBytes(string image_name)
    Byte[] bytes = null;
    if (!string.IsNullOrEmpty(image_name))
        string app_path = ((System.Web.HttpRequestWrapper)this.Request)
        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;

The main code looks like this:

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");
    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");
    ReportDocument rp = new ReportDocument();
    rp.Load(System.Web.HttpContext.Current.Server.MapPath("~/Reports/") + "Test.rpt");
                            "image_list_" + DateTime.Now);
    return Json(new
        data = "ok",
        results = 1,
        success = true,
        errors = String.Empty
    }, JsonRequestBehavior.AllowGet);