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();

 

posted @ 2020-08-07 15:29  芈璐  阅读(3651)  评论(0编辑  收藏  举报