日期:2014-05-19  浏览次数:20994 次

求把图片存入数据库和从数据库还原的程序
想把图片转化成流写入数据库,并能从数据库读出并重新转换回图片,但重新转换试了N次都失败,不能转换回原来的团片,请大侠指点一下,具体怎样实现,谢谢

------解决方案--------------------
把图片存入ACCESS数据库二进制字段
OpenFileDialog openfile = new OpenFileDialog();
String FileName = " ";
if (openfile.ShowDialog() == DialogResult.OK)
{
FileName = openfile.FileName;
this.pictureBox1.Image = Image.FromFile(FileName);

FileStream objFileStream;

objFileStream = new FileStream(FileName, FileMode.Open, FileAccess.Read);
byte[] fileData = new byte[objFileStream.Length];

string strConnection = @ "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\db1.mdb ";

//把文件流填充到数组
objFileStream.Read(fileData, 0, fileData.Length);
OleDbConnection connection = new OleDbConnection(strConnection);
OleDbCommand cmd = new OleDbCommand( "update My_Main set My_Text= " + "@Image where My_ID=40 ", connection);
cmd.Parameters.Add(new OleDbParameter( "@Image ", fileData));
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
objFileStream.Close();
}


从ACCESS数据库二进制字段还原图片

string strDSN = @ "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\db1.mdb ";
string strSQL = "select * from My_Main where My_ID = 40 ";
OleDbConnection myConn = new OleDbConnection(strDSN);
OleDbCommand myCmd = new OleDbCommand(strSQL, myConn);
OleDbDataReader datareader = null;
try
{
myConn.Open();
datareader = myCmd.ExecuteReader();

if (datareader.Read())
{

if (datareader[ "My_Text "] is System.Byte[])
{
ImageConverter imc = new ImageConverter();
pictureBox1.image = imc.ConvertFrom(null, System.Globalization.CultureInfo.CurrentCulture, datareader[ "My_Text "]) as Image;


}
}
}
catch
{
}
finally
{
myConn.Close();
}

------解决方案--------------------
//入SQL Server
using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;

class BLOBDemo
{
[STAThread]
static void Main(string[] args)
{
Add( "Test ", "2.jpg ");
}

public static void Add(string categoryName, string filePath)
{
// byte [] photo = GetPhoto(filePath);

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);

byte [] photo = br.ReadBytes((int)fs.Length);

br.Close();
fs.Close();

SqlConnection cn = new SqlConnection( "Data Source = (local);Integrated Security = SSPI;Initial Catalog=Northwind ");
SqlCommand cmd = new SqlCommand( "INSERT INTO Categories(CategoryName, Picture) VALUES (@CategoryName, @Picture) ", cn);

cmd.Parameters.Add( "@CategoryName ",