做S1结业项目MyQQ时,学生问我将图片存入数据库的方法,在此略作小结,以供参考。
.jpg) 作者:北大青鸟南京中博-张宪芝 南京航空航天大学计算机技术研究生,曾前往德国交流,多年高校及软件开发公司工作经验。
做S1结业项目MyQQ时,学生问我将图片存入数据库的方法,在此略作小结,以供参考。
一、保存至数据库 byte[] bytes = sdr[14] is DBNull ? null : sdr.GetSqlBinary(14).Value; if (bytes == null || bytes.Length == 0) { book.BooksImage = null; } else { MemoryStream ms = new MemoryStream(bytes); book.BooksImage = Image.FromStream(ms); ms.Close(); } 二、保存至数据库 byte[] bytes=null; if(book.BooksImage!=null) { book.BooksImage.Save("temp.dat"); FileStream fs=new FileStream("temp.dat",FileMode.Open); bytes=new byte[fs.Length]; fs.Read(bytes,0,bytes.Length); fs.Close(); } sp[13]=new SqlParameter("@BookImage",bytes); i = DBHelper.ExecuteNonQuery(INSERT, CommandType.Text, sp); 三、窗口修改时,需要注意的地方(其它信息修改,图片未改会报错): if (picBook.Image != null) { Bitmap img = new Bitmap(picBook.Image.Width, picBook.Image.Height); Graphics g = Graphics.FromImage(img); g.DrawImage(picBook.Image, new Point(0, 0)); img.Save("a.dat"); FileStream fs = new FileStream("a.dat",FileMode.Open); byte[] bs = new byte[fs.Length]; fs.Read(bs, 0, bs.Length); b.BookImage = Image.FromStream(fs); fs.Close(); } 希望同学们能通过本文,增强自己的学习能力,更为重要的是能够举一反三。
|