C # operations picture read and store SQL Server implementation Code _c# tutorial

Source: Internet
Author: User
First, use C # to convert image to byte[] and insert the database:
1.1 Convert Image control image to stream:
Copy Code code as follows:

Private byte[] Pictoarray ()
{
Bitmap BM = new Bitmap (picbox.image);
MemoryStream ms = new MemoryStream ();
Bm. Save (MS, Imageformat.jpeg);
Return Ms. GetBuffer ();
}

Copy Code code 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 the picture file into a byte stream and insert the database:
Copy Code code as follows:

Class Imageinserter
{
public static int insertimg (string path)
{
----------read a picture in a file and convert it into a byte stream
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 ();
}
}
}

Second, take picture data out of SQL Server and display it on the PictureBox control:
Copy Code code 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);
}
Related Article

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.