找了好久关于数据库存储图片的代码,无奈全是WEB版的,而且整一堆窗体按纽的,很是不爽,今天终于整理出来了(高手别见笑,我正在高手ing^_^)
关于在数据库中怎么存储并读取其实很简单,关键是如何将图片转换成二进制码,并且又如何从二进制码再还原成图片.当然大家需要注意的是数据库中要把存储图片的字段定义为Binary就行了.关键的代码如下
考下去就能运行,当然kevin.gif图片您得自己复制过去了
using System;
using System.IO;
namespace ConsoleApplication1
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
FileStream fs = new FileStream(@"../../kevin.gif",FileMode.Open);
byte[] by = new byte[fs.Length];
fs.Read(by,0,(int)fs.Length);
foreach(byte a in by)
Console.Write(a);
fs = new FileStream(@"../../waston.bmp",FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs);
fs.Write(by,0,by.Length);

}
}
}

解决方案 »

  1.   


    FileStream fs=File.OpenRead(@"E:\image003.jpg");
    byte[] content=new byte[fs.Length];
    fs.Read(content, 0,content.Length);
    fs.Close();

    byte[] content=new byte[40394];
    conn.Open();
    string sql ="select data from test where no=@no";
    SqlCommand comm=new SqlCommand(sql,conn);
    comm.Parameters.Add("@no",SqlDbType.Int).Value=1;
    content=(byte[])comm.ExecuteScalar();
    FileStream fw=new FileStream(@"d:\test.jpg",FileMode.OpenOrCreate,FileAccess.ReadWrite);
    fw.Write(content,0,content.Length);
    fw.Close();