Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Windows.Forms;
Using System.IO;
Using System.Data.SqlClient;
Namespace Xuankeform
{
public partial class Formimage:form
{
Public Formimage ()
{
InitializeComponent ();
}
private void Button1_Click (object sender, EventArgs e)
{
Openfiledialog1.filter = "*jpg|*.jpg|*bmp|*.bmp|*gif|*.gif";
DialogResult dia = Openfiledialog1.showdialog ();
if (dia = = DialogResult.OK)
{
string filename = Openfiledialog1.filename;
FileStream fs = new FileStream (filename,filemode.open,fileaccess.read);//Read the picture into the stream
byte[] imagebytes = new Byte[fs. length];//binary Array to temporarily store the binary encoding of the image
BinaryReader br = new BinaryReader (fs);//Binary Reader
Imagebytes = Br. Readbytes (Convert.ToInt32 (fs. Length));//Read the picture into a binary array
Start connection database into database
SqlConnection conn = new SqlConnection ("server=.; Database=schooldata;user=sa;pwd= ");
Conn. Open ();
SqlCommand cmd = conn. CreateCommand ();
Cmd.commandtext = "INSERT into tutable values (@image)";
Cmd. Parameters.clear ();
Cmd. Parameters.Add ("@image", imagebytes);
Cmd. ExecuteNonQuery ();
Conn. Close ();
MessageBox.Show ("Image upload success");
}
}
Read
private void Button2_Click (object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection ("server=.; Database=schooldata;user=sa;pwd= ");
Conn. Open ();
SqlCommand cmd = conn. CreateCommand ();
Cmd.commandtext = "SELECT top 1 *from tutable";
SqlDataReader dr = cmd. ExecuteReader ();
Dr. Read ();
Byte[] Imgbytes = (byte[]) dr["Tuxiang"];
Write an image to memory
MemoryStream ms = new MemoryStream (imgbytes, 0, Imgbytes. Length);
Ms. Write (imgbytes, 0, Imgbytes. Length);
Image img = image.fromstream (ms);
This.pictureBox1.SizeMode = Pictureboxsizemode.zoom;
This.pictureBox1.Image = img;
}
}
}
Image upload Read code