Binary data saves the picture to the database and reads the database binary data display picture

Source: Internet
Author: User

I. Browse pictures

OpenFileDialog ofd = new OpenFileDialog ();
Ofd. InitialDirectory = @ "E:\";
Ofd. Filter = "Image Files (*. bmp;*. jpg;*. GIF) |*. bmp;*. jpg;*. Gif| All Files (*. *) |*.* ";
Ofd. Restoredirectory = true;

if (OFD. ShowDialog () = = DialogResult.OK)
{
Picaddress = ofd. FileName;
Image imge = Image.FromFile (picaddress);
Bitmap BM = new Bitmap (Imge, Picbox.width, picbox.height);
Picbox.image = BM;
}

Two. Save the image to the database

Read the database and get the field where you want to save the picture, convert the picture to binary data and save it to the database

byte[] pic = getcontent (the path to the picture);
Comyindfo.logo = field Saved by pic;//database

<summary>
Convert a picture's file into binary data saved to a database
</summary>
<param name= "filepath" ></param>
<returns></returns>

public static byte[] GetContent (string filepath)//Convert files under the specified path to binary code for transfer to database
{
FileStream fs = new FileStream (filepath, FileMode.Open, FileAccess.Read);
byte[] Bydata = new Byte[fs. length];//creating a new byte array to hold the file stream
Fs. Read (bydata, 0, bydata.length);//Reading file stream
Fs. Close ();
return bydata;
}

Three. Reading binary data from a database and displaying pictures

byte[] Imagebytes = Item. logo;//read a field from a database
MemoryStream ms = new MemoryStream (imagebytes);
Bitmap bmpt = new Bitmap (MS);
pictureBox1.Image = bmpt;

Binary data saves the picture to the database and reads the database binary data display picture

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.