将图像转换为字节流

3

我在数据库中有一个带有图像路径的字段。 我需要将图像转换为字节数组以在Crystal Reports中使用。 由于这些图像已经在我的根目录中,我不想使用上传功能。 有没有办法可以实现这一点?


1
使用 File.ReadAllBytes 将文件加载到字节数组中。 - Lasse V. Karlsen
1
可能是重复的问题:如何将图像转换为字节数组 - user5147454
1个回答

1

在研究了这个问题之后,我找到了一个适合我的解决方案。

customerReport.SetDataSource(dt); 之前,我调用了这个方法:showImageonReport(dt);

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

    }

将图片从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>");
    }
}

重要提示:当您在创建数据集时添加image_stream时,请记得在数据库中添加此列,并将其声明为VARBINARY(MAX)
这样就可以完成任务了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接