원본 위치 <http://support.microsoft.com/kb/309158/KO/>
프로젝트 만들기
1. |
MyImages라는 테이블을 SQL Server Northwind 데이터베이스에 추가합니다. 테이블에 다음 필드를 포함시킵니다.
| ||||||
2. |
Visual Studio .NET을 시작한 다음 새로운 Visual C# Windows 응용 프로그램 프로젝트를 만듭니다. | ||||||
3. |
도구 상자에서 기본 폼 Form1로 두 Button 컨트롤을 끕니다. | ||||||
4. |
속성 창에서 Button1의 텍스트 속성을 Save to Database(from File)로 변경하고 Button2의 Text 속성을 Save to File(from Database)로 변경합니다. | ||||||
5. |
코드 창의 맨 위에 다음 코드를 추가합니다. using System.Data; | ||||||
6. |
Button1을 두 번 누르고 다음 코드를 Button1_Click 이벤트 처리기에 추가합니다. 참고 Uid <user name>은 데이터베이스에서 이러한 작업을 수행할 권한을 갖고 있어야 합니다. { | ||||||
7. |
Button2를 두 번 누르고 다음 코드를 Button2_Click 이벤트 처리기에 추가합니다. 참고 Uid <user name>은 데이터베이스에서 이러한 작업을 수행할 권한을 갖고 있어야 합니다. { | ||||||
8. |
F5 키를 눌러 응용 프로그램을 컴파일하고 실행합니다. | ||||||
9. |
Save to Database(from File)를 눌러 이미지 C:\WinNT\Gone Fishing.bmp를 SQL Server Image 필드로 로드합니다. | ||||||
10. |
Save to File(from Database)을 눌러 SQL Server Image 필드의 데이터를 파일로 저장합니다. |
데이터베이스에서 Visual C#의 PictureBox 컨트롤로 그림 직접 복사
원본 위치 <http://support.microsoft.com/kb/317701/ko>
예제
1. |
구조가 다음과 같은 SQL Server나 Access 테이블을 만듭니다. CREATE TABLE BLOBTest |
2. |
Visual Studio .NET을 열고 새 Visual C# Windows 응용 프로그램 프로젝트를 만듭니다. |
3. |
도구 상자에서 기본 Form1에 PictureBox와 두 Button 컨트롤을 추가합니다. Button1의 Text 속성을 File to Database로 설정하고 Button2의 Text 속성을 Database to PictureBox로 설정합니다. |
4. |
폼의 코드 모듈 맨 위에 다음 using 문을 삽입합니다. using System.Data.SqlClient; |
5. |
public class Form1 : System.Windows.Forms.Form 클래스 선언 안에 데이터베이스 연결 문자열에 대한 다음 선언을 추가하고 필요한 경우 연결 문자열을 조정합니다. String strCn = "Data Source=localhost;integrated security=sspi;initial catalog=mydata"; |
6. |
Button1(File to Database)의 Click 이벤트 프로시저에 다음 코드를 삽입합니다. 필요한 경우 사용할 수 있는 샘플 이미지 파일의 파일 경로를 조정합니다. 이 코드는 디스크에서 Byte 배열로 이미지를 읽은 다음(FileStream 개체 사용) 이 데이터를 매개 변수화된 Command 개체를 사용하여 데이터베이스에 삽입합니다. try |
7. |
Button2(Database to PictureBox)의 Click 이벤트 프로시저에 다음 코드를 삽입합니다. 이 코드는 데이터베이스의 BLOBTest 테이블에서 DataSet로 행을 가져오고 가장 최근에 추가된 이미지를 Byte 배열로 복사한 다음 MemoryStream 개체로 복사하고 MemoryStream을 PictureBox 컨트롤의 Image 속성으로 로드합니다. try |
8. |
F5 키를 눌러 프로젝트를 컴파일하고 실행합니다. |
9. |
File to Database 단추를 눌러서 최소한 하나 이상의 예제 이미지를 데이터베이스로 로드합니다. |
10. |
Database to PictureBox 단추를 눌러 PictureBox 컨트롤에 저장된 이미지를 표시합니다. |
11. |
PictureBox 컨트롤에서 데이터베이스로 직접 이미지를 삽입할 수 있으려면 세 번째 Button 컨트롤을 추가하고 Click 이벤트 프로시저에 다음 코드를 삽입합니다. 이 코드는 PictureBox 컨트롤에서 MemoryStream 개체로 이미지 데이터를 가져오고 MemoryStream을 Byte 배열로 복사한 다음 매개 변수화된 Command 개체를 사용하여 Byte 배열을 데이터베이스에 저장합니다. try |
12. |
프로젝트를 실행합니다. Database to PictureBox 단추를 눌러 PictureBox 컨트롤에 이전에 저장한 이미지를 표시합니다. 새로 추가된 단추를 눌러 PictureBox에서 데이터베이스로 이미지를 저장합니다. 그런 다음 Database to PictureBox 단추를 다시 눌러서 이미지가 제대로 저장되었는지 확인합니다. |
===================================================================================================
How to Store or Save Image in SQL Server table
원본 위치 <http://www.shabdar.org/store-save-images-in-sql-server.html>
To store an image in to sql server, you need to read image file into a byte array. Once you have image data in byte array, you can easity store this image data in sql server using sql parameters. Following code explains you how to do this.
private void cmdSave_Click(object sender, EventArgs e) { try { //Read Image Bytes into a byte array byte[] imageData = ReadFile(txtImagePath.Text); //Initialize SQL Server Connection SqlConnection CN = new SqlConnection(txtConnectionString.Text); //Set insert query string qry = "insert into ImagesStore (OriginalPath,ImageData) _ values(@OriginalPath, @ImageData)"; //Initialize SqlCommand object for insert. SqlCommand SqlCom = new SqlCommand(qry, CN); //We are passing Original Image Path and //Image byte data as sql parameters. SqlCom.Parameters.Add(new SqlParameter("@OriginalPath", (object)txtImagePath.Text)); SqlCom.Parameters.Add(new SqlParameter("@ImageData", (object)imageData)); //Open connection and execute insert query. CN.Open(); SqlCom.ExecuteNonQuery(); CN.Close(); //Close form and return to list or images. this.Close(); }
Following code explains how to read image file in to a byte array.
//Open file in to a filestream and //read data in a byte array. byte[] ReadFile(string sPath) { //Initialize byte array with a null value initially. byte[] data = null; //Use FileInfo object to get file size. FileInfo fInfo = new FileInfo(sPath); long numBytes = fInfo.Length; //Open FileStream to read file FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read); //Use BinaryReader to read file stream into byte array. BinaryReader br = new BinaryReader(fStream); //When you use BinaryReader, you need to
//supply number of bytes to read from file. //In this case we want to read entire file.
//So supplying total number of bytes. data = br.ReadBytes((int)numBytes); return data; }
How to read image data bytes from SQL Server table
To read images from SQL Server, prepare a dataset first which will hold data from SQL Server table. Bind this dataset with a gridview control on form.
void GetImagesFromDatabase() { try { //Initialize SQL Server connection. SqlConnection CN = new SqlConnection(txtConnectionString.Text); //Initialize SQL adapter. SqlDataAdapter ADAP = new SqlDataAdapter("Select * from ImagesStore", CN); //Initialize Dataset. DataSet DS = new DataSet(); //Fill dataset with ImagesStore table. ADAP.Fill(DS, "ImagesStore"); //Fill Grid with dataset. dataGridView1.DataSource = DS.Tables["ImagesStore"]; } catch(Exception ex) { MessageBox.Show(ex.ToString()); } }
Once you have image data in grid, get image data from grid cell. Alternatively you can also get image data from Dataset table cell.
//Store image to a local file. pictureBox1.Image.Save("c:\test_picture.jpg",
System.Drawing.Imaging.ImageFormat.Jpeg);
If you want you can extend this code to save image from Picture Box to a local image file.
//Store image to a local file.
pictureBox1.Image.Save("c:\test_picture.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
Points of Interest
If you see frmImageStore in design mode, I have placed picturebox1 into a panel. This panel's AutoScroll property is set to True and SizeMode property of PictureBox1 is set to True. This allows picturebox to resize itself to the size of original picture. When picturebox's size is more than Panel1's size, scrollbars becomes active for Panel.