使用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);

运行结果:

 

posted @ 2016-06-07 22:38  张杨  阅读(4060)  评论(0编辑  收藏  举报