MSSQL image storage and read display

Source: Internet
Author: User

1. Create a test data table:
Create Table Test ([imageid] [int] identity (1, 1) not null, BMP image)

2. store image files in the database:
// Sqlconnection connection
String sqlstr = string. Format ("insert into test (BMP) values (@ I)", combobox1.text );
If (conn. State = connectionstate. Closed)
Conn. open ();
If (conn. State = connectionstate. open)
{
Sqlcommand cmd = new sqlcommand (sqlstr, Conn );
Filestream stream = new filestream ("1.png", filemode. Open );
Int Len = (INT) stream. length;
Byte [] bytes = new byte [Len];
Stream. Read (bytes, 0, Len );
Cmd. Parameters. Add ("@ I", sqldbtype. Image, Len );
Cmd. Parameters ["@ I"]. value = bytes;
Cmd. executenonquery ();

Stream. Close ();
}
Else
{
MessageBox. Show ("failed to open database connection .");
}
Conn. Close ();

3. Read the image from the database and display it in picturebox:

Bindingsource source = new bindingsource ();

Source. positionchanged + = new eventhandler (source_positionchanged );

// create a bindingnavigator data navigation control on the form. When a data table is opened and moved between data items, the following event method is triggered:
void source_positionchanged (Object sender, eventargs e)
{< br> byte [] image_bytes = (byte []) (datarowview) source. current ). row ["BMP"];
memorystream stream = new memorystream (image_bytes);
picturebox1.image = image. fromstream (Stream);
stream. close ();
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.