C # operating on image reading and storing SQLserver implementation code

Source: Internet
Author: User

1. Use C # to convert the Image to byte [] and insert it into the database:
1.1 convert the Image of the Image control into a stream: Copy codeThe Code is as follows: private byte [] PicToArray ()
{
Bitmap bm = new Bitmap (picBox. Image );
MemoryStream MS = new MemoryStream ();
Bm. Save (MS, ImageFormat. Jpeg );
Return ms. GetBuffer ();
}

Copy codeThe Code is as follows:
// Save to database
Try
{
String SQL = "update T_Employee set ImageLogo = @ ImageLogo where EmpId = @ EmpId ";
SqlHelper. ExecuteNonQuery (SQL, new SqlParameter ("@ ImageLogo", imgSourse ));
MessageBox. Show ("Modify saved! "); // ShowInfo (0 );
}
Catch (Exception ex)
{
MessageBox. Show ("update failed! "+ Ex. Message );
Return;
}

1.2 convert image files into word throttling and insert them into the database:Copy codeThe Code is as follows: class ImageInserter
{
Public static int InsertImg (string path)
{
// ---------- Read images as files and convert them into word-based throttling
FileStream fs = new FileStream (path, FileMode. Open );
Byte [] imgSourse = new byte [fs. Length];
Fs. Read (imgSourse, 0, imgSourse. Length );
Fs. Close ();
Using (SqlConnection conn = new SqlConnection (SqlHelper. connStr ))
{
Conn. Open ();
Using (SqlCommand cmd = conn. CreateCommand ())
{
Cmd. CommandText = "update T_Employee set ImageLogo = @ ImageLogo ";
// Cmd. Parameters. Add ("@ ImageLogo", SqlDbType. Image );
Cmd. Parameters. Add (new SqlParameter ("@ ImageLogo", imgSourse ));
Return cmd. ExecuteNonQuery ();
}
}
}

2. Extract the image data from SQLserver and display it on the pictureBox control:Copy codeThe Code is as follows: byte [] ImageLogoArray = row ["ImageLogo"] is DBNull? Null :( byte []) (row ["ImageLogo"]);
MemoryStream MS = null;
If (ImageLogoArray! = Null)
{
MS = new MemoryStream (ImageLogoArray );
PicBox. Image = new Bitmap (MS );
}

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.