木偶的Blog

博客园 首页 新随笔 联系 订阅 管理

二进制数组在数据库中可以用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();
                    }
                }
            }
        }

将图片转化成二进制的数组然后再存储进数据库的方法需要浪费大量的服务器资源,故不建议使用,一般的做法是将图片的地址保存进数据库,但是这中做法的缺点是一旦改变图片位置将无法读取文件。

posted on 2006-03-29 12:08  SoulPuppet  阅读(260)  评论(0)    收藏  举报