Use C # to access the network image and local image (in the form of a binary stream) in SQL Server ),
First, it is common to store our local images and convert them into binary streams and store them in the table corresponding to the database.
The Code is as follows:
String path = ".. /.. /A.jpg "; FileStream fs = new FileStream (path, FileMode. open); int streamLength = (int) fs. length; // obtain the Length of the file stream. Byte [] image = new byte [streamLength]; // declares a byte array for saving the image file fs. read (image, 0, streamLength); // converts an image file into a byte array to save fs. close (); var p = new pictureUrl {pictureUrl1 = image}; db. pictureUrl. insertOnSubmit (p); // insert records using the linq statement. Db. SubmitChanges ();
This situation is often used, but there are other cases. For example, if we want to access an image on the network, but do not want to download it to a local location, it is very troublesome, you only want to convert the image
Binary stream, stored in the database.
The Code is as follows:
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();
The code used to read images is the same as the code used to read images.
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);
Running result: