簡體   English   中英

無法將byte []轉換為圖像

[英]unable to convert byte[] to image

我正在嘗試檢索存儲在MS SQL Server數據庫中的圖片。 列的類型是圖像。 我的代碼是:

try
{
    SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString);
    SqlCommand cmd = new SqlCommand(string.Empty, con);
    cmd.CommandText = "select Picture from Person";
    con.Open();
    SqlDataReader dataReader = cmd.ExecuteReader();
    dataReader.Read();

    byte[] image = new byte[10000];
    long len = dataReader.GetBytes(0, 0, image, 0, 10000);

    using (MemoryStream stream = new MemoryStream(image))
    {
        stream.Seek(0, SeekOrigin.Begin);
        pictureBox1.Image = Image.FromStream(stream);
    }
    con.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

設置pictureBox1.Image屬性時,我不斷收到ArgumentException因為參數無效 我嘗試了Internet上所有可用的解決方案,但徒勞無功。

即使圖像較小(或較大),也始終使用10000字節數組。 不要手動創建byte[] ,如果需要, DataReader可以提供整個字節數組。

byte[] image = reader.GetFieldValue<byte[]>(0);

如果您不使用.NET 4.5,則可以要求字段並手動進行轉換。

byte[] image = (byte[])reader.GetValue(0);

但是,您只使用第一行中的第一列這一事實根本不需要DataReader ,而只需使用ExecuteScalar() (我也正在清理您的代碼以使用正確的using語句,並將ex.Message切換為ex.ToString()以便在錯誤對話框中提供更多信息)。

try
{
    using(SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString))
    using(SqlCommand cmd = new SqlCommand(string.Empty, con))
    {
        cmd.CommandText = "select Picture from Person";
        con.Open();

        byte[] image = (byte[])cmd.ExecuteScalar();

        using (MemoryStream stream = new MemoryStream(image))
        {
            pictureBox1.Image = Image.FromStream(stream);
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

嘗試這個 :

SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString);
SqlCommand cmd = new SqlCommand(string.Empty, con);
cmd.CommandText = "select Picture from Person";
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
dataReader.Read();
byte[] image = new byte[10000];
long len = dataReader.GetBytes(0, 0, image, 0, 10000);
using (MemoryStream mStream = new MemoryStream(image))
{
    pictureBox1.Image = Image.FromStream(mStream);
}

暫無
暫無

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

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