簡體   English   中英

如何從 SQL 表轉換二進制數據(檢查其圖像類型)並在 Winforms C# 上顯示

[英]How to convert binary data from SQL table (check if its image type) and display it on Winforms C#

我正在嘗試使用二進制從 SQL Server 讀取數據,檢查文件類型是否為圖像,然后使用 C# 在 Windows 窗體中顯示它。 我在兩天內搜索了解決方案我找到了一些很好的例子,但它們對我不起作用,這是我的代碼如下:

public byte[] byteArrayIn { get; set; }
    public Image img { get; set; }
    public Image convertImage(string id)
    {
        SqlConnection con = new SqlConnection(conString);
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT Doc_Invoice FROM Repairs WHERE ID ="+id, con);
        SqlDataReader reader = cmd.ExecuteReader();
        if (reader.Read())
            byteArrayIn = (byte[])reader["Doc_Invoice"];
        using (var ms = new MemoryStream(byteArrayIn))
        {
            if (IsValidImage(byteArrayIn))
            {
                img = Image.FromStream(ms);
            }
        }
        return img;
    }
    public static bool IsValidImage(byte[] bytes)
    {
        try
        {
            using (MemoryStream ms = new MemoryStream(bytes))
                Image.FromStream(ms);
        }
        catch (ArgumentException)
        {
            return false;
        }
        return true;
    }

我從另一種形式調用這個方法,比如

picRequest.Image = db.convertImage(id.ToString());

伙計們只有一個問題,我的代碼有什么問題? :( 這是 SQL 結果 在此處輸入圖片說明

伙計們,我得到了答案,我想,我也需要知道你們的答案 所以我存儲到 SQL Server 中的二進制數據是從 MS Access (OFFICE 365) 存儲的,所以我認為 MS Access 在將 IMG 轉換為時將他的標題添加到圖片中二進制

你認為呢? 或者如果有人可以幫助我找到多少字節使用 MS Access for Header? 我將在 Access 的 Header 之后開始讀取 IMG 字節,例如:

using (var ms = new MemoryStream(bytes,[MS Access Header byte],bytes.Length - [MS Access Header byte]))
        {
            return Image.FromStream(ms);
        }

暫無
暫無

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

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