An image access method in the database
1. Reading data of image type
Methods for reading image type data can be grouped into the following steps:
1 Use the unsigned byte array to hold the value of the image Type field of the table in the database corresponding to the data set. For example:
Byte[] bytes= (byte[]) Image Type field value
2 Use the MemoryStream class, which creates a stream that supports storage as memory. That is, the stream created by the MemoryStream class is supported as memory rather than as a disk or network connection. Its constructors are:
Public MemoryStream (byte[] buffer);
3 Use the Bitmap class, which encapsulates the GDI + bitmap, which consists of the pixel data of the graphic image and its attributes. The Bitmap object is an object that is used to process an image defined by pixel data. Its constructors are:
Public Bitmap (Stream stream);
4 Displays the image using the PictureBox control object in the form.
2. Save data of Image type
The method of saving image type data is also divided into the following steps:
1 using the Stream class, first obtain the stream object from the image file, and then use the Read method of the class to read the binary data into the byte array from the image file. The Read method is:
public abstract int Read ([in, out] byte[] buffer, int offset, int count);
2 The value in the byte array is stored in the Image field of the table in the database corresponding to the data set. The format is:
The image Type field = bytes;
3 Update the database, you can complete the function of saving image data.
Examples of image access in a database
The following is an example of how to access images in a SQL Server database.
(1) Create a Windows application and design the form interface as shown in the illustration.
⑵ Add a namespace reference
using System.Data;
using System.Data.SqlClient;
using System.IO;
⑶ Add a field declaration
private string connString="server=localhost; integrated security=sspi; database=pubs";
SqlConnection conn;
SqlDataAdapter adapter;
DataSet dataset;