简体   繁体   English

将图像转换为字节流

[英]Convert Image to Byte Stream

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. 我需要将图像转换为字节数组以在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? 有什么办法可以实现吗?

After researching on the problem I found a solution that works for me. 在研究了这个问题后,我发现了一个适合我的解决方案。

Before customerReport.SetDataSource(dt); customerReport.SetDataSource(dt);之前customerReport.SetDataSource(dt);

I call this method: showImageonReport(dt); 我称这个方法为: showImageonReport(dt);

dt is the datatable: "Image" is the column name which hold paths to the image dt是数据表: "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 用于将图像从url加载到字节流

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) 重要的是要注意,当您在创建的数据集中添加image_stream时,请记住在数据库中添加此列并将其声明为VARBINARY(MAX)

This should do the job 这应该做的工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM