C# 將圖片以二進制保存,讀取二進制轉換圖片


首先定義數據庫連接字符串:

String strCn = "server=.;database=DB_NAME;user=sa;pwd=XXX";

讀取圖片,將圖片轉換二進制保存到數據庫方法:

            SqlConnection cn = new SqlConnection(strCn);
            SqlCommand cmd = new SqlCommand("INSERT INTO ProductID_Image (ProductID,ImageData) VALUES ('1',@BLOBData)", cn);
            String strBLOBFilePath = @"C:/Users/Administrator/Desktop/打印模板.jpeg";
            FileStream fsBLOBFile = new FileStream(strBLOBFilePath, FileMode.Open, FileAccess.Read);
            Byte[] bytBLOBData = new Byte[fsBLOBFile.Length];
            fsBLOBFile.Read(bytBLOBData, 0, bytBLOBData.Length);
            fsBLOBFile.Close();
            SqlParameter prm = new SqlParameter("@BLOBData", SqlDbType.VarBinary, bytBLOBData.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, bytBLOBData);
            cmd.Parameters.Add(prm);
            cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();

讀取數據庫中二進制數據,轉換成圖片方法:

            SqlConnection cn = new SqlConnection(strCn);
            cn.Open();
            SqlCommand cmd = new SqlCommand("select ProductID,ImageData from ProductID_Image", cn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "ProductID_Image");
            int c = ds.Tables["ProductID_Image"].Rows.Count;
            if (c > 0)
            {
                Byte[] byteBLOBData = new Byte[0];
                byteBLOBData = (Byte[])(ds.Tables["ProductID_Image"].Rows[c - 1]["ImageData"]);
                MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
                pictureBox1.Image = Image.FromStream(stmBLOBData);
            }
            cn.Close();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM