3

I've a field in my Database with image path. I need to convert the image to byte array to be used in Crystal Reports. Since the images are already in my root directory I don't want to use the upload function. Is there any way I can achieve this?

MAK
  • 1,250
  • 21
  • 50
  • 1
    To load a file into a byte array, use `File.ReadAllBytes`. – Lasse V. Karlsen Jul 27 '15 at 06:38
  • 1
    possible duplicate of [How to convert image in byte array](http://stackoverflow.com/questions/3801275/how-to-convert-image-in-byte-array) –  Jul 27 '15 at 06:43

1 Answers1

1

After researching on the problem I found a solution that works for me.

Before customerReport.SetDataSource(dt);

I call this method: showImageonReport(dt);

dt is the datatable: "Image" is the column name which hold paths to the image

private void showImageonReport(DataTable dt)
    {

        for (int index = 0; index < dt.Rows.Count; index++)
        {
            if (dt.Rows[index]["Image"].ToString() != "")
            {
                string s = this.Server.MapPath(
                            dt.Rows[index]["Image"].ToString());

                if (File.Exists(s))
                {
                    LoadImage(dt.Rows[index], "image_stream", s);
                }
                else
                {
                    LoadImage(dt.Rows[index], "image_stream",
                              "DefaultPicturePath");
                }
            }
            else
            {
                LoadImage(dt.Rows[index], "image_stream",
                          "DefaultPicturePath");
            }
        }

    }

For loading the image from url to byte stream

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

It is important to note that when you're adding image_stream in the dataset you create, remember to add this column in your Database as well and declare it to be VARBINARY(MAX)

This should do the job

MAK
  • 1,250
  • 21
  • 50