C # stores picture information directly in the database

Source: Internet
Author: User

Recently made a small project, you need to put the picture information directly in the database, rather than the picture path in the database, the practice is

The field type of photo in the database table is the image type

string filepath = @ "C:\Users\Administrator\Desktop\ photo \1.jpg"; Path to the local picture
FileStream fs = new FileStream (filepath, FileMode.Open, FileAccess.Read);
int length = Convert.ToInt32 (fs. Length);
Byte[] B = new Byte[length];
Fs. Read (b, 0, length);
String sql = "Update LKZPB set [email protected],[email protected] where lk_id=" + count;
SqlParameter PMS = new SqlParameter ("@photo", sqldbtype.image);
Pms. Value = b;

Perform an operation to update the database, SqlHelper is the encapsulated operation of the database
Result + = Sqlhelper.executenonquery (sql, PMS);

After performing the above operation, the image is stored in the corresponding fields in the database.

The following will get the picture information from the database and display it in PictureBox

First add a PictureBox on the WinForm interface with the name PictureBox1

String strsearch = "SELECT * from LKZPB where lk_id=1";

Storing the queried data in a DataTable
DataTable dt = sqlhelper.executedatatable (strsearch);

Get information about the photo field in the database, convert it to byte[] array type, and the first column in DT is the information of photo in the No. 0 row
byte[] bytes = (byte[]) dt. ROWS[0][1];


Stream stream = new MemoryStream (bytes);

int length = Convert.ToInt32 (stream. Length);
byte[] Insertbte = new Byte[length];
Stream. Read (insertbte, 0, length);

Image image = Image.fromstream (stream, true);

Show pictures in PictureBox
pictureBox1.Image = Image;

C # stores picture information directly in the database

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.