Asp.net (c #) implements code for accessing binary images from sqlserver

Source: Internet
Author: User

The following describes the main implementation ideas:
1. Access Images
(1) convert the image file to binary and directly store it in SQL server
Copy codeThe Code is as follows:
// UploadHelper. cs
/// <Summary>
/// Convert the image into a long binary
/// </Summary>
/// <Param name = "photopath"> </param>
/// <Returns> </returns>
Public static Byte [] SetImgToByte (string imgPath)
{
FileStream file = new FileStream (imgPath, FileMode. Open, FileAccess. Read );
Byte [] byteData = new Byte [file. Length];
File. Read (byteData, 0, byteData. Length );
File. Close ();
Return byteData;
}
/// <Summary>
/// Save the image converted to binary code to the database
/// </Summary>
Public static bool SaveEmployeeImg2Db (Employee model, string path)
{
Try
{
Byte [] imgBytes = SetImgToByte (path );
Model. Photo = imgBytes;
Bool flag = EmployeeService. SaveEmployeePhoto (model); // EmployeeService is called by the internal database of the company, and photos are inserted or updated. Details are not provided here.
Return flag;
}
Catch (Exception ex)
{
Throw ex;
}
}

(2) upload images on the webpage
Copy codeThe Code is as follows:
/// <Summary>
/// Upload an image
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Protected void btnUpload_Click (object sender, EventArgs e)
{
String serverPath = Server. MapPath ("~ /Images /");
If (this. fuPhoto. HasFile) // fuPhoto is the fileupload Control
{
String fileName = this. fuPhoto. PostedFile. FileName;
FileInfo fi = new FileInfo (fileName );
String mimeType = this. fuPhoto. PostedFile. ContentType. ToLower ();
If (mimeType. IndexOf ("image") <0)
{
// ("The format of the uploaded photo is incorrect ");
}
Else if (fi. Length> 2*1024*1024)
{
// Process the image larger than 2 MB
}
Else
{
String saveFilePath = serverPath + DateTime. Now. ToString ("yyyyMMddHHmmss") + fileName;
Try
{
// First save the image to the server
This. fuPhoto. PostedFile. SaveAs (saveFilePath );
// Convert to binary
Employee model = new Employee (int. Parse (id); // id is the Employee id, which is a simulated field.
Bool flag = UploadHelper. SaveEmployeeImg2Db (model, saveFilePath );
}
Catch
{
// ("Photo upload failed ");
}
Finally
{
// Delete the image
If (System. IO. File. Exists (saveFilePath ))
{
System. IO. File. Delete (saveFilePath );
}
}
}
}
Else
{
// ("Select all the photos to upload ");
}
}

(3) retrieve photos from the database (the returned Image Format)
Copy codeThe Code is as follows:
// UploadHelper. cs
/// <Summary>
/// Convert binary into Image
/// </Summary>
/// <Param name = "photopath"> </param>
/// <Returns> </returns>
Public static System. Drawing. Image GetImgFromByte (Employee model)
{
System. Drawing. Image img = null;
Try
{
Stream stream = new MemoryStream (model. Photo );
Img = System. Drawing. Image. FromStream (stream, false );
}
Catch
{
Img = null;
}
Return img;
}

After this method is obtained, you can assign a value to the Image attribute of a PictureBox directly under winform. However, the web does not have such a powerful control, so the following steps are taken.
2. directly display images in the form of streams on the webpage
(1) generate the image stream page (ImgHelper. aspx)
There is no design page for this page. The class file is as follows:
Copy codeThe Code is as follows:
Using System;
Using System. Data;
Using System. Configuration;
Using System. Collections;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Using System. Collections. Generic;
Using System. IO;
/// <Summary>
/// Image helper class
/// </Summary>
Public partial class ImgHelper: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
If (! String. IsNullOrEmpty (Request ["employeeId"]) // id of the employee passing on the page to display the photo
{
Int employeeId = int. Parse (Request ["employeeId"]);
Employee model = // EmployeeService. GetEmployeeByCondition (new Employee (Employee ID) [0] as Employee; // The internal function is used to find details that an Employee does not disclose.
Try
{
Byte [] byteImg = model. Photo;
Stream stream = new MemoryStream (byteImg );
System. Drawing. Bitmap img = (System. Drawing. Bitmap) System. Drawing. Bitmap. FromStream (stream, false); // convert to Bitmap
Response. Buffer = false;
Response. ContentType = "image/jpg ";
Response. AddHeader ("Content-Disposition", "attachment?filename=photo.jpg"); // The photo name is photo.jpg.
Response. BinaryWrite (byteImg); // write the binary stream
Response. End ();
}
Catch
{
Response. End ();
}
}
}
}

(2) Call ImgHelper. aspx to display the photo page
When loading a page, assign the following values to the image control:
Copy codeThe Code is as follows:
This. imgPhoto. ImageUrl = "/ImgHelper. aspx? EmployeeId = "+ tmpEmployee. Id. ToString (); // imgPhoto is an image control.

In general, it is very convenient for winform to store and retrieve data, but for webform, we need to have a slightly conversion idea. It would be better to write controls that are directly bound to an Image object like winform. The code above has passed the test and I hope it will help you.

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.