如何把圖片轉換成二進制存入數據庫


 

 

public static byte[] imgBytesIn;//用來存儲圖片的二進制
Stream ms;
byte[] picbyte;
//在創建數據庫鏈接,測試鏈接成功后,在高級里可自動生成鏈接數據庫字符串,copy出來即可
string str = "Data Source=PC-20180AIHL;Initial Catalog=Image;User ID=sa";
OpenFileDialog openF = new OpenFileDialog();

 

//獲取用戶打開的路徑然轉換成二進制存入數據庫
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP";

if (ofd.ShowDialog() == DialogResult.OK)
{
string filePath = ofd.FileName;//圖片路徑
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] imageBytes = new byte[fs.Length];
BinaryReader br = new BinaryReader(fs);
imageBytes = br.ReadBytes(Convert.ToInt32(fs.Length));//圖片轉換成二進制流

string strSql = string.Format("insert into image(tupian) values('" + imageBytes + "')");
int count = Write(strSql, imageBytes);

if (count > 0)
{
MessageBox.Show("成功!");
}
else
{
MessageBox.Show("失敗!");
}
}

 

讀出:

byte[] imagebytes = null;

//打開數據庫

SqlConnection con = new SqlConnection("server=PC-2018AIHL;uid=sa;pwd=123456;database=Image");

con.Open();

SqlCommand com = new SqlCommand("select * from image where ID=1", con);

SqlDataReader dr = com.ExecuteReader();

byte[] dd = null;
string id = null;
while (dr.Read())
{
dd = (byte[])dr["tupian"];
id = dr["ID"].ToString();
imagebytes = (byte[])dr.GetValue(1);

}

dr.Close();

com.Clone();

con.Close();

MemoryStream ms = new MemoryStream(imagebytes);

Bitmap bmpt = new Bitmap(ms);

pictureBox1.Image = bmpt;

 


免責聲明!

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



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