Objective:To insert into & retrieve images from SQL server database without using stored procedures and also to perform insert, search, update and delete operations & navigation of records. Introduction:As we want to insert images into the database, first we have to create a table in the database, we can use the data type 'image' or 'binary' for storing the image.Query for creating table in our application: create table student(sno int primary key,sname varchar(50),course varchar(50),fee money,photo image) Converting image into binary data: We can't store an image directly into the database. For this we have two solutions: To store the location of the image in the databaseConverting the image into binary data and insert that binary data into database and convert that back to image while retrieving the records.
If we store the location of an image in the database, and suppose if that image is deleted or moved from that location, we will face problems while retrieving the records. So it is better to convert image into binary data and insert that binary data into database and convert that back to image while retrieving records. We can convert an image into binary data usingFileStream
MemoryStream
1. FileStream uses file location to convert an image into binary data which we may/may not provide during updation of a record. Example: FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
byte[] photo_aray = new byte[fs.Length];
fs.Read(photo_aray, 0, photo_aray.Length); 2. So it is better to use MemoryStream which uses image in the PictureBox to convert an image into binary data.Example:
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo_aray = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_aray, 0, photo_aray.Length);Read more: C# Corner
If we store the location of an image in the database, and suppose if that image is deleted or moved from that location, we will face problems while retrieving the records. So it is better to convert image into binary data and insert that binary data into database and convert that back to image while retrieving records. We can convert an image into binary data usingFileStream
MemoryStream
1. FileStream uses file location to convert an image into binary data which we may/may not provide during updation of a record. Example: FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
byte[] photo_aray = new byte[fs.Length];
fs.Read(photo_aray, 0, photo_aray.Length); 2. So it is better to use MemoryStream which uses image in the PictureBox to convert an image into binary data.Example:
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo_aray = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_aray, 0, photo_aray.Length);Read more: C# Corner
0 comments:
Post a Comment