Display Dynamic Image in Crystal Report .NET
If you have imagepath that store in your database, Crystal Report .NET in Visual Studio 2003/2005 cannot display image file dynamically unless you use dynamic image location feature in Crystal Report XI.
But don't worry, it can display with some work around for this.
- You must have imagepath in your database.
- Create new Dataset/XML Schema (xsd) to use as resource data in creating report. Add an additional field that is not in the table and which is of type base64Binary :
<xs:element name="image_stream" type="xs:base64Binary" minOccurs="0" /> - When designing a report drag and drop the "image_stream" field in the region where you want it to appear.
- Add the following method in you code:
private void AddImageColumn(DataTable objDataTable, string strFieldName)
{
try
{
DataColumn objDataColumn = new DataColumn(strFieldName, Type.GetType("System.Byte[]"));
objDataTable.Columns.Add(objDataColumn);
}
catch (Exception ex)
{
Response.Write("<font color=red>"+ex.Message+"</font>");
}
} - And this one to load the image:
private void LoadImage(DataRow objDataRow, string strImageField, string FilePath)
{
try
{
FileStream fs = new FileStream(FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] Image = new byte[fs.Length];
fs.Read(Image, 0, Convert.ToInt32(fs.Length));
fs.Close();
objDataRow[strImageField] = Image;
}
catch (Exception ex)
{
Response.Write("<font color=red>"+ex.Message+"</font>");
}
} - Before assigning the dataset to the "SetDataSource" of your report, add the following code:
AddImageColumn(ds.Tables[0], "image_stream");
for (int index=0; index < ds.Tables[0].Rows.Count; index++)
{
if (ds.Tables[0].Rows[index]["image_path"].ToString() != "")
{
if(File.Exists(this.Server.MapPath(ds.Tables[0].Rows[index]["image_path"].ToString())))
{
LoadImage(ds.Tables[0].Rows[index], "image_stream", ds.Tables[0].Rows[index]["image_path"].ToString());
}
else
{
LoadImage(ds.Tables[0].Rows[index], "image_stream", "C:\NoImage.jpg");
}
}
else
{
LoadImage(ds.Tables[0].Rows[index], "image_stream", "C:\NoImage.jpg");
}
} - And finally to display report in crystal report viewer
crDoc.SetDatabaseLogon(UserID, Password, Server, Database);
crDoc.SetDataSource(ds.Tables[0]);
CrystalReportViewer1.ReportSource = crDoc;