簡體   English   中英

將圖像轉換為字節流

[英]Convert Image to Byte Stream

我的數據庫中有一個帶有圖像路徑的字段。 我需要將圖像轉換為字節數組以在Crystal Reports中使用。 由於圖像已經在我的根目錄中,我不想使用上傳功能。 有什么辦法可以實現嗎?

在研究了這個問題后,我發現了一個適合我的解決方案。

customerReport.SetDataSource(dt);之前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)

這應該做的工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM