C # database to store pictures, read pages show

    A Web site, the picture data must exist; how to deal with storing pictures, there are a lot of ways.

    Own summary in two ways: 1, save the picture as a static document form; (advantages: easy file transfer, backup; Disadvantages: not easy to recover lost files) 2, the picture is converted into a stream of bytes eligible for other ways to obtain a complete picture data storage ( advantages: save the database, easily lost; drawback: the database space is growing rapidly)    

    Before saving the picture is not the picture of the original content is processed by the file name and other basic information stored; recently wanted to carry out another way to save picture data; special record.

    Save the file complete information, common way is to convert the file to a binary stream, saved to the database, of course, you can save the image as a base64 data stream.

    1, tools: database SQLServer 2012 R2; development languages: C #; display formats: for web display processing by MVC.

    2, the core database field describes the image information table: the FileContent a varbinary (max) NULL , ---- image content storage field, the field type  varbinary (max) -> C # in the corresponding field type byte []  

    3, get a picture file byte stream (for database storage)    

        ///  <Summary> 
        /// Returns the path of the image based on the image byte stream byte []
         ///  </ Summary> 
        ///  <param name = "the imagePath"> Image Path </ param> 
        ///  <Returns > returns the byte stream </ returns> 
        public  static  byte [] getImageByte ( String the imagePath) 
        { 
            the FileStream Files = new new the FileStream (the imagePath, FileMode.Open);
             byte [] = imgByte new new  byte [files.Length]; 
            files.Read (imgByte, 0 , imgByte.Length); 
            files.Close (); 
            return imgByte;
        }

    4, the acquired images stored in the database byte stream    

            ///  <the Summary> 
            /// add images to the content information database
             ///  </ the Summary> 
            ///  <param name = "path"> </ param> 
            ///  <returns A> </ returns A> 
            public  static  int InsertImg ( String path) 
            { 
                // ---------- way the document image read and converted into a byte stream 
                the FileStream FS = new new the FileStream (path, FileMode.Open);
                 byte [] = imgSourse new new  byte [fs.Length]; 
                fs.Read (imgSourse, 0 , imgSourse.Length); 
                fs.Close (); 
                //--------------读取图片并转化成字节流结束----------------

                using (SqlConnection conn = new SqlConnection(SqlHelper.connStr))
                {
                    conn.Open();
                    using (SqlCommand cmd = conn.CreateCommand())
                    {
                        //cmd.CommandText = "update PictureInfo set FileContent=@ImageLogo ";
                        cmd.CommandText = "insert into PictureInfo (FileContent) VALUES FileContent=@fileContent";
                        //cmd.Parameters.Add("@fileContent", System.Data.SqlDbType.Image);
                        cmd.Parameters.Add(new SqlParameter("@fileContent", imgSourse));
                        return cmd.ExecuteNonQuery();
                    }
                }
            }        

     5, read the information in the database images to show the page (Winform There Picture controls can be used directly Image display; MVC need to do some processing.)

      (1), Winform in show        

        ///  <Summary> 
        /// show a single image to the page
         ///  </ Summary> 
        public  void ReturnImageShow () 
        { 
            // ..... data acquisition process is omitted
             // Get a picture stored in the byte stream 
            byte [] ImageLogoArray = Row [ " FileContent " ] IS DBNull? null : ( byte []) (Row [ " FileContent " ]); 
            MemoryStream MS = null ;
             IF (ImageLogoArray =! null ) 
            { 
                MS= new MemoryStream(ImageLogoArray);
                this.picBox.Image = new Bitmap(ms);
            }
        }

       (2), MVC is shown in (background)      

         // GET: Pictures / Index 
        ///  <the Summary> 
        /// data display method (using js foreground processing, call the rendering img src)
         ///  </ the Summary> 
        ///  <returns A> </ returns A> 
        public ActionResult Index () 
        { 
            the using (DbContext the DataContext = new new the DataContext ()) 
            { 
                // Get a list of data to be presented 
                PictureInfoService InfoService = new new PictureInfoService (DbContext);                
                 var userList = dbContext.Set <PictureInfo> ();
                 // pass the value list <T > data 
                ViewData [ " PicInfo" ] = UserList.ToList (); 
            } 

            return View (); 
        }       


        // the GET: Pictures / IndexAdv 
        ///  <Summary> 
        /// display data (background image label directly spliced content page using the page directly by value method rendering)
         ///  </ Summary> 
        ///  <Returns> </ Returns> 
        public ActionResult IndexAdv () 
        { 
            the using (DbContext the DataContext = new new the DataContext ()) 
            { 
                // get the data 
                PictureInfoService InfoService = new new PictureInfoService (DbContext) ;
                 var userList = dbContext.Set <PictureInfo>();
                 // background formatting text directly read 
                the StringBuilder Builder = new new the StringBuilder ();
                 the foreach ( var Data in userList) 
                { 
                    // Here src attribute byte stream back to point assignment requires conversion method 
                    builder.AppendFormat ( " <div class = \ "item \"> <img id = \ "image {0} \" src = \ "../ Pictures / ReturnPic? id = {1} & random = Math.random () \" title = \ "{ } 2 \ "/> </ div> " , data.id, data.id, data.FileName); 
                } 
                // background mosaic page tab
                 // the MVC (non-Core) identifying reception using HTML @ Html.Raw (ViewBag .DataBuilder)
                = ViewBag.DataBuilder builder.toString (); 
            } 
            return View (); 
        } 

        ///  <Summary> 
        /// Returns image (add background image processing method of the byte stream)
         ///  </ Summary> 
        ///  <param name = "id"> query (id index) </ param> 
        ///  <Returns> </ Returns> 
        public FileStreamResult ReturnPic ( int ID) 
        { 
            the using (DbContext the DataContext = new new the DataContext ()) 
            { 
                // the present using the the EF, only exemplary; main acquired image corresponding to contents information byte [] 
                PictureInfoService InfoService = new newPictureInfoService (DbContext);
                 var Data = infoService.Find <PictureInfo> (ID);
                 // the acquired byte stream into the MemoryStream, for returning
                 // the MVC byte stream in front display images, require special handling,
                 // return type FileStreamResult 
                the MemoryStream MS = new new the MemoryStream (data.FileContent);
                 return  new new FileStreamResult (MS, " Image / JPEG " ); 
            } 
        }             

       (3), MVC show reception section

          IndexAdv.cshtml

          

 

           Index.cshtml 

                                    

 

             

 

         6, the general image conversion encapsulation byte stream

    using System.Drawing;
    using System.IO;
    public class ImgTransHelper
    {
        /// <summary>
        /// 图片转换成字节流
        /// </summary>
        /// <param name="img">要转换的Image对象</param>
        /// <returns>转换后返回的字节流</returns>
        public static byte[] ImgToByt(Image img)
        {
            MemoryStream ms = new MemoryStream();
            byte[] imagedata = null;
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            imagedata = ms.GetBuffer();
            return imagedata;
        }

        /// <summary>
        /// 字节流转换成图片
        /// </summary>
        /// <param name="byt">要转换的字节流</param>
        /// <returns>转换得到的Image对象</returns>
        public static Image BytToImg(byte[] byt)
        {
            MemoryStream ms = new MemoryStream(byt);
            Image img = Image.FromStream(ms);
            return img;
        }

        /// <summary>
        /// 根据图片路径返回图片的字节流byte[]
        /// </summary>
        /// <param name="imagePath">图片路径</param>
        /// <returns>返回的字节流</returns>
        private static byte[] getImageByte(string imagePath)
        {
            FileStream files = new FileStream(imagePath, FileMode.Open);
            byte[] imgByte = new byte[files.Length];
            files.Read(imgByte, 0, imgByte.Length);
            files.Close();
            return imgByte;
        }
    }

        以上为记录内容,如有不足之处,欢迎指正!

Guess you like

Origin www.cnblogs.com/skyheaving/p/12387594.html