日期:2014-05-17 浏览次数:20811 次
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Data.SqlClient; using System.Drawing; namespace WindowsFormsApplication5 { class MyImageClass { private static string sqlConString;//连接字符串 public static string SqlConString { get { return MyImageClass.sqlConString; } set { MyImageClass.sqlConString = value; } } /// <summary> /// 将图片保存至数据库 /// </summary> /// <param name="fileName">图片全路径</param> /// <param name="name">保存的图片名称</param> /// <returns>返回成功或失败</returns> public static bool SaveImage(string fileName,string name) { SqlConnection con = new SqlConnection(SqlConString); SqlCommand cmd = con.CreateCommand(); FileStream fs = new FileStream(fileName, FileMode.Open); byte[] MyData = new byte[fs.Length]; fs.Read(MyData, 0, (int)fs.Length); fs.Close(); SqlParameter pname = new SqlParameter("@name", name); cmd.Parameters.Add(pname); SqlParameter pimage = new SqlParameter("@image", MyData); cmd.Parameters.Add(pimage); cmd.CommandText = "insert into MyTable values (@name,@image)"; con.Open(); int result = cmd.ExecuteNonQuery(); con.Close(); if (result == 1) return true; else return false; } /// <summary> /// 从数据库读取相应图片 /// </summary> /// <param name="name">图片名称</param> /// <returns>返回该图片</returns> public static Image GetImage(string name) { SqlConnection con = new SqlConnection(SqlConString); SqlCommand cmd = con.CreateCommand(); SqlParameter pname = new SqlParameter("@name", name); cmd.Parameters.Add(pname); cmd.CommandText = "select image from MyTable where name=@name"; con.Open(); byte[] MyData = (byte[])cmd.ExecuteScalar(); MemoryStream ms = new MemoryStream(MyData, 0, MyData.Length); ms.Seek(0, SeekOrigin.Begin); Image image = Image.FromStream(ms); con.Close(); return image; } } }
------解决方案--------------------
http://www.cnblogs.com/tuyile006/archive/2007/01/08/614718.html
------解决方案--------------------
二进制保存到数据库。然后在读取出来。
------解决方案--------------------
数据库虽然可以保存图片,但本人不建议你用图片直接保存在数据库。具体的应该是你把图片的相对路径保持在数据库,至于为什么不要把图片存入数据库你自己看下相关文章
http://www.csdn.net/article/2012-05-15/2805584