Image upload Read code

Source: Internet
Author: User

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

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.