如何从C#中的数据库中获取图像?

时间:2011-03-01 06:15:39

标签: c# sql-server visual-studio-2008

我没有将图像变成二进制形式,但是现在想从数据库中获取图像数据。 所以你能对此提出这样的想法吗? 我已经像下面这样插入图片:

FileDialog dialog = new OpenFileDialog();
dialog.InitialDirectory = @":D\";
dialog.Filter = "(*.jpg;*.gif;*.jpeg;*.bmp)| *.jpg; *.gif; *.jpeg; *.bmp";
if (dialog.ShowDialog() == DialogResult.OK)
{
    imagename = dialog.FileName;
    pictureBox1.Image = Image.FromFile(imagename);
}
dialog = null;

然后它也存储在数据库中,但现在我必须以下一种形式检索图像我该怎么办?

4 个答案:

答案 0 :(得分:2)

protected void butSubmit_Click(object sender, EventArgs e)
{
SqlConnection connection = null;
try
 {
 Byte[] imgByte = null;
   if (FileUpload1.HasFile && FileUpload1.PostedFile != null)
{
 HttpPostedFile File = FileUpload1.PostedFile;
imgByte = new Byte[File.ContentLength];
 File.InputStream.Read(imgByte, 0, File.ContentLength);
 }
 connection = new SqlConnection(ConfigurationManager.ConnectionStrings         
 "ConnectionString"].ConnectionString.ToString());

 connection.Open();
string sql = "INSERT INTO Table1(title,image) VALUES(@theTitle, @theImage) SELECT     
@@IDENTITY";
 SqlCommand cmd = new SqlCommand(sql, connection);
 cmd.Parameters.AddWithValue("@theTitle", txtTitle.Text);
 cmd.Parameters.AddWithValue("@theImage", imgByte);
 int id = Convert.ToInt32(cmd.ExecuteScalar());
 lblStatus.Text = String.Format("ID is {0}", id);

 Image1.ImageUrl = "~/DisplayImg.ashx?id=" + id;
}
{
lblStatus.Text = "There was an error";
}
finally
{
 connection.Close();
}

}

答案 1 :(得分:1)

    int O_id =Convert.ToInt32(textBox2.Text);

            SqlConnection cn = new SqlConnection(strCn);
            SqlCommand cmd = new SqlCommand("INSERT INTO BLOBTest (BLOBData, O_id) VALUES (@BLOBData,'"+O_id+"')", cn);
            String strBLOBFilePath = textBox1.Text;//Modify this path as needed.


            //Read jpg into file stream, and from there into Byte array.
            FileStream fsBLOBFile = new FileStream(strBLOBFilePath, FileMode.Open, FileAccess.Read);
            Byte[] bytBLOBData = new Byte[fsBLOBFile.Length];
            fsBLOBFile.Read(bytBLOBData, 0, bytBLOBData.Length);
            fsBLOBFile.Close();

            //Create parameter for insert command and add to SqlCommand object.
            SqlParameter prm = new SqlParameter("@BLOBData", SqlDbType.VarBinary, bytBLOBData.Length, ParameterDirection.Input, false,
                        0, 0, null, DataRowVersion.Current, bytBLOBData);
            cmd.Parameters.Add(prm);

            //Open connection, execute query, and close connection.
            cn.Open();
            cmd.ExecuteNonQuery();
            MessageBox.Show("Picture has been uploaded");
            cn.Close();

答案 2 :(得分:0)

好的,假设您将图像存储为数据库中的BLOB字段,以下代码检索BLOB字段数据,创建内存流并从内存流中加载Bitmap

using (SqlConnection conn = ...)
{
    conn.Open();

    using (SqlCommand cmd = new SqlCommand("SELECT Picture FROM <tableName> WHERE ...", conn)
    using (SqlDataReader reader = cmd.ExecuteReader())
    {
        if (reader.Read())
        {
            byte[] picData= reader["Picture"] as byte[] ?? null;

            if (picData!= null)
            {
                using (MemoryStream ms = new MemoryStream(picData))
                {
                    // Load the image from the memory stream. How you do it depends
                    // on whether you're using Windows Forms or WPF.
                    // For Windows Forms you could write:
                    System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms);
                }
            }
        }
    }
}

答案 3 :(得分:0)

using System.Data.SqlClient;


using System.Drawing;

using System.Data;

using System.IO;

using System.Drawing.Imaging;


public void Save_Image(Object sender, EventArgs e)
{

    // Create a byte[] from the input file

    int len = Upload.PostedFile.ContentLength;
    byte[] pic = new byte[len];
    Upload.PostedFile.InputStream.Read (pic, 0, len);

    // Insert the image into the database

    SqlConnection connection = new
 SqlConnection (@"server=abc\.SQLEXPRESS;database=Storage;uid=sa;pwd=sa");

    try
    {
        connection.Open ();
        SqlCommand cmd = new SqlCommand ("insert into Image " 
          + "(Picture) values (@pic)", connection);

        cmd.Parameters.Add ("@pic", pic);
        cmd.ExecuteNonQuery ();

    }
    finally 
    {
        connection.Close ();
    }
}

我们只将字节图像存储到表名中&#34; Image&#34; 它只包含一列。 将字节图像存储到数据库中会占用大量数据库大小 用于大型图像存储和从数据库中检索特定图像 使用搜索需要更长的时间进行处理。这会导致 低性能和存储问题。