Converting an image to a byte stream

I have a field in my database with an image outline. I need to convert an image to a 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 a way to achieve this?

+3


source to share


1 answer


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

Before customerReport.SetDataSource(dt);

I am calling this method: showImageonReport(dt);

dt

is datatable: "Image"

is the name of the column that contains the 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");
            }
        }

    }

      



To load 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 add image_stream

to the created dataset, remember to add this column to your database and declare itVARBINARY(MAX)

This should do the job

+1


source







All Articles