使用C#向Sql Sever中存取網絡圖片和本地圖片(二進制流的形式)


先是做普通的,存儲我們本地的圖片,將它轉化為二進制流存儲到數據庫對應的表中。

代碼如下:

 

  string path = "../../A.jpg";
            FileStream fs = new FileStream(path, FileMode.Open);
            int streamLength = (int)fs.Length;  //獲取文件流的長度。  
            byte[] image = new byte[streamLength];    //聲明字節數組,用於保存圖片文件  
            fs.Read(image, 0, streamLength);    //把圖片文件轉換成為字節數組保存  
            fs.Close();
            var p = new pictureUrl
            {
                pictureUrl1 = image
            };
            db.pictureUrl.InsertOnSubmit(p);//此處使用linq語句實現插入記錄。
            db.SubmitChanges();

 

這種情況使用的比較多,但是也有其他情況,比如我們想要存取網絡上的一張圖片,但是又不想將它下載到本地,覺得很麻煩,只想通過圖片的路徑,將它轉成

二進制流,存到數據庫中。

代碼如下

 

            string path = "https://img3.doubanio.com/mpic/s8896281.jpg";
            Uri url = new Uri(path);
            WebRequest webRequest = WebRequest.Create(url);
            WebResponse webResponse = webRequest.GetResponse();
            Bitmap myImage = new Bitmap(webResponse.GetResponseStream());

            MemoryStream ms = new MemoryStream();
            myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            var p = new pictureUrl
            {
                pictureUrl1 = ms.ToArray()
            };
            db.pictureUrl.InsertOnSubmit(p);
            db.SubmitChanges();

 

讀取圖片的代碼,兩者一樣,都是通過image控件在前台顯示

  var pictures = from picture in db.pictureUrl select picture;
            pictureUrl myPicture = pictures.First();
            MemoryStream mymemorystream = new MemoryStream(myPicture.pictureUrl1.ToArray());
            pictureBox1.Image = Image.FromStream(mymemorystream);

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM