当我从数据库中获取图像然后我得到错误:参数无效 [英] When I Fetching Image From Database Then I Got Error : Parameter Is Not Valid

查看:78
本文介绍了当我从数据库中获取图像然后我得到错误:参数无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void button1_Click(object sender,EventArgs e)

{

//显示图片

this.Cursor = Cursors.WaitCursor;

con = new SqlConnection(Data Source = GT-9 \\ SQLEXPRESS; Initial Catalog = BMS_Express; User ID = sa; Password = 123);

MemoryStream stream = new MemoryStream();

try

{

DataSet ds = new DataSet();

con.Open();

SqlDataAdapter ad = new SqlDataAdapter(从tbl_image中选择照片,其中id = 1,con);

ad.Fill(ds);

DataTable dt = ds.Tables [0];

if(dt.Rows.Count> 0)

{

byte [] image =(byte [])dt.Rows [0] [photo];

MemoryStream ms1 = new MemoryStream(image);

ms1.Seek(0,SeekOrigin.Begin);

pictureBox1.Image = Image.FromStream(ms1); //(错误:参数无效)

}



}

finally

{

con.Close();

stream.Close();

}

this.Cursor = Cursors.Default;

}

private void button1_Click(object sender, EventArgs e)
{
// Show Image
this.Cursor = Cursors.WaitCursor;
con = new SqlConnection("Data Source=GT-9\\SQLEXPRESS;Initial Catalog=BMS_Express;User ID=sa;Password=123");
MemoryStream stream = new MemoryStream();
try
{
DataSet ds = new DataSet();
con.Open();
SqlDataAdapter ad = new SqlDataAdapter("select photo from tbl_image where id=1", con);
ad.Fill(ds);
DataTable dt = ds.Tables[0];
if (dt.Rows.Count > 0)
{
byte[] image = (byte[])dt.Rows[0]["photo"];
MemoryStream ms1 = new MemoryStream(image);
ms1.Seek(0, SeekOrigin.Begin);
pictureBox1.Image = Image.FromStream(ms1); //(Error : Parameter is not valid)
}

}
finally
{
con.Close();
stream.Close();
}
this.Cursor = Cursors.Default;
}

推荐答案

1.您不需要使用 SqldataAdapter 用于从数据库中读取图像,您应该使用 SqlCommand ,而不是在下一个示例中:

1.You do not need to use SqldataAdapter for reading image from database, you should use SqlCommand instead like in the next example:
IDataReader reader = null;
byte[] imageData = null;
            //
            try
            {
                IDbCommand dbCommand = new SqlCommand(); 
                dbCommand.Connection = con;
                dbCommand.CommandText = string.Format("select photo from tbl_image where id=1);
                //
                reader = dbCommand.ExecuteReader();
                //
                if (reader.Read())
                {
                    imageData = (byte[])reader["photo"];
                }
            }
            finally
            {
                if (reader != null)
                    reader.Close();
                //
                con.Close();
            }



2.然后你应该像你一样使用这个数据:


2.Then you should use this data similar like you did:

if(imageData != null)
{
  MemoryStream ms = new MemoryStream(imageData);
  pictureBox1.Image = System.Drawing.Image.FromStream(ms);
}


这篇关于当我从数据库中获取图像然后我得到错误:参数无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆