二进制数组在数据库中可以用Image类型的字段或者Binary类型的字段来保存
/// <summary>
/// Make picture to byte array
/// </summary>
/// <returns>the File byte array</returns>
public static byte[] PictureInput()
{
FileInfo fi=new FileInfo("pic/gwj.jpg"); //relace your picture's path
if(fi.Exists) //judge the object of FileInfo is Exists or not
{
byte[] bData=null; //declare a byte array
using(FileStream fs=fi.OpenRead()) //read the file to the FileStream
{
bData=new byte[fi.Length]; //initialize the byte array
int nReadlength=fs.Read(bData,0,(int)fi.Length); //change the file to byte array
fs.Close();
}
}
return bData;
}
/// <summary>
/// change the byte array to the file
/// </summary>
/// <param name="bData">the File byte array</param>
public static void PictureOutput(byte[] bData)
{
if(!bData=null) //judge the byte array is null or not
{
FileInfo fi=new FileInfo("pic/gwj1.jpg"); //initialize a object of FileInfo
if(!fi.Exists) //judge the FileInfo object is exist or not
{
using(FileStream fs=fi.Create()) //if it is not exists use it's creat method
{
fs.Write(bData,0,bData.Length); //write the file from byte Array
fs.Close();
}
}
else //else it is exists use it's openWrite method
{
using(FileStream fs=fi.OpenWrite())
{
fs.Write(bData,0,bData.Length); //write the file from byte Array
fs.Close();
}
}
}
}
将图片转化成二进制的数组然后再存储进数据库的方法需要浪费大量的服务器资源,故不建议使用,一般的做法是将图片的地址保存进数据库,但是这中做法的缺点是一旦改变图片位置将无法读取文件。
浙公网安备 33010602011771号