C # pictures are saved to the database and the pictures are read from the database and displayed

Source: Internet
Author: User

How to save a picture to a database:

public void Imgtodb (String sql)
{//parameter SQL required to save the IMGE variable name is @images
Call method such as: Imgtodb ("Update Userphoto set[email protected]where userno= ' "+ temp +" ' ");
FileStream fs = File.openread (T_photo. Text);
byte[] Imageb = new Byte[fs. Length];
Fs. Read (Imageb, 0, Imageb. Length);
Fs. Close ();
SqlCommand COM3 = new SqlCommand (Sql,con);
COM3. Parameters.Add ("@images", Sqldbtype.image). Value = Imageb;
if (COM3. Connection.state = = connectionstate.closed)
COM3. Connection.Open ();
Try
{
COM3. ExecuteNonQuery ();
}
Catch
{ }
Finally
{COM3. Connection.close (); }
}

a picture is read in the database and displayed in the PictureBox Medium:

Method One:
private void ShowImage (String sql)
{
Call methods such as: ShowImage ("Select Photo from Userphoto where userno= '" + Userno + "'");
SqlCommand cmd = new SqlCommand (SQL, conn);
Conn. Open ();
Byte[] b= (byte[]) cmd. ExecuteScalar ();
if (b.length〉0)
{
MemoryStream stream = new MemoryStream (b, true);
Stream. Write (b, 0, b.length);
pictureBox1.Image = new Bitmap (stream);
Stream. Close ();
}
Conn. Close ();
}

Method Two: When a row is selected in the DG:
private void Dg_mouseup (object sender, MouseEventArgs e)
{
Entire row selection
if (E.button = = System.Windows.Forms.MouseButtons.Left)
{//user number, name, gender, social Security number, hometown, college, Department, campus, department, phone, photo
Show Photos
Object IMGOBJ=DG[10, DG. Currentrow.index]. Value;
if (imgobj! = NULL &&!) Convert.isdbnull (Imgobj))
{
Byte[] Imgb = (byte[]) imgobj;
MemoryStream memstream = new MemoryStream (IMGB);
Try
{
Bitmap myimge = new Bitmap (memstream);
This.pictureBox1.Image = Myimge;
}
Catch
{
Db.msgbox ("Failed to read the photo from the database! ");
}
}
Else
pictureBox1.Image = null;
}

Use C # database access for images

This article summarizes how to save pictures in. NET WinForm and. NET WebForm (ASP) to SQL Server and read the displayed methods.
1. Use ASP. To upload and save the image to SQL Server, and then read and display it from SQL Server:
1) upload and deposit to SQL Server

Database structure
CREATE TABLE Test
{
ID identity (+),
Fimage image
}
Related stored procedures
Create proc UpdateImage
(
@UpdateImage Image
)
As
Insert into Test (fimage) VALUES (@UpdateImage)
GO
Add the following in the Upphoto.aspx file:
<input id= "Upphoto" name= "Upphoto" runat= "Server" type= "file" >
<asp:button id= "Btnadd" name= "Btnadd" runat= "server" text= "upload" ></asp:Button>
Then add the Btnadd button's Click event handling code in the post-code file UpPhoto.aspx.cs:
private void btnAdd_Click (object sender, System.EventArgs e)
{
Acquire images and convert images to byte[]
Httppostedfile Upphoto=upphoto.postedfile;
int upphotolength=upphoto.contentlength;
Byte[] Photoarray=new byte[upphotolength];
Stream Photostream=upphoto.inputstream;
Photostream.read (photoarray,0,upphotolength);
Connecting to a database
SqlConnection conn=new SqlConnection ();
Conn. connectionstring= "Data source=localhost;database=test; User Id=sa; Pwd=sa ";
SqlCommand cmd=new SqlCommand ("UpdateImage", conn);
Cmd.commandtype=commandtype.storedprocedure;
Cmd. Parameters.Add ("@UpdateImage", sqldbtype.image);
Cmd. parameters["@UpdateImage"]. Value=photoarray;
If you want to add a picture without using a stored procedure, change the above four lines to:
String strsql= "Insert into Test (fimage) VALUES (@FImage)";
SqlCommand cmd=new SqlCommand (strsql,conn);
Cmd. Parameters.Add ("@FImage", sqldbtype.image);
Cmd. parameters["@FImage"]. Value=photoarray;
Conn. Open ();
Cmd. ExecuteNonQuery ();
Conn. Close ();
}
2) Read and display from SQL Server
Add the following code where you want the picture to appear:
<asp:image id= "Imgphoto" runat= "Server" imageurl= "showphoto.aspx" ></asp:image>
Showphoto.aspx Body Code:
private void Page_Load (object sender, System.EventArgs e)
{
if (! Page.IsPostBack)
{
SqlConnection conn=new SqlConnection ()
Conn. connectionstring= "Data source=localhost;database=test; User Id=sa; Pwd=sa ";
String Strsql= "select * from Test where id=2";//This assumes that a picture with ID 2 is obtained
SqlCommand cmd=new SqlCommand (strsql,conn);
Conn. Open ();
SqlDataReader Reader=cmd. ExecuteReader ();
Reader. Read ();
Response.contenttype= "Application/octet-stream";
Response.BinaryWrite ((byte[]) reader["Fimage"]);
Response.End ();
Reader. Close ();
}
}

2. Save the picture to SQL Server in WinForm and read it from SQL Server and display it in PictureBox
1), deposit into SQL Server
The database structure and the use of the stored procedure, the same as above
First, add a OpenFileDialog control to the form, named Ofdselectpic;
Then, add an open File button on the form and add the following click event code:
Stream MS;
Byte[] Picbyte;
Ofdselectpic.showdialog ();
if (Ofdselectpic.showdialog () ==dialogresult.ok)
{
if ((Ms=ofdselectpic.openfile ())!=null)
{
MessageBox.Show ("OK");
Picbyte=new Byte[ms. Length];
Ms. position=0;
Ms. Read (Picbyte,0,convert.toint32 (Ms. Length));
MessageBox.Show ("Read!");
Connecting to a database
SqlConnection conn=new SqlConnection ();
Conn. connectionstring= "Data source=localhost;database=test; User Id=sa; Pwd=sa ";
SqlCommand cmd=new SqlCommand ("UpdateImage", conn);
Cmd.commandtype=commandtype.storedprocedure;
Cmd. Parameters.Add ("@UpdateImage", sqldbtype.image);
Cmd. parameters["@UpdateImage"]. Value=picbyte;
Conn. Open ();
Cmd. ExecuteNonQuery ();
Conn. Close ();
Ms. Close ();
}
}
2) Read and display in PictureBox
First, add a PictureBox, named Ptbshow
Then, add a button that adds the following response event:
SqlConnection conn=new SqlConnection ();
Conn. connectionstring= "Data source=localhost;database=test; User Id=sa; Pwd=sa ";
String strsql= "Select Fimage from Test where id=1";
SqlCommand cmd=new SqlCommand (strsql,conn);
Conn. Open ();
SqlDataReader Reader=cmd. ExecuteReader ();
Reader. Read ();
MemoryStream ms=new MemoryStream ((byte[]) reader["Fimage"]);

Image Image=image.fromstream (ms,true);
Reader. Close ();
Conn. Close ();
Ptbshow.image=image;

C # pictures are saved to the database and the pictures are read from the database and displayed

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.