asp.net (C #) code to access binary pictures from SQL Server _ practical Tips

Source: Internet
Author: User
Here are the main ways to achieve this:
1, access to pictures
(1) Convert picture file to binary and save directly into SQL Server
Copy Code code as follows:

//uploadhelper.cs
///<summary>
///convert picture to Long binary
/// ;/summary>
///<param name= "Photopath" ></param>
///<returns></returns>
Publi C Static byte[] Setimgtobyte (string imgpath)
{
FileStream file = new FileStream (Imgpath, FileMode.Open, FILEAC Cess. Read);
byte[] bytedata = new Byte[file. Length];
file. Read (bytedata, 0, bytedata.length);
file. Close ();
Return bytedata;
}
///<summary>
///saves a picture converted to binary code to the database
///</summary>
public static bool Saveemplo YEEIMG2DB (Employee model, string path)
{
Try
{
byte[] imgbytes = setimgtobyte (path);
Model. Photo = imgbytes;
BOOL Flag=employeeservice.saveemployeephoto (model);//employeeservice is a library call inside the company, insert or update photos, no details are revealed here
return Flag
}
catch (Exception ex)
{
Throw ex;
}
}

(2), upload the picture in the webpage
Copy Code code as follows:

<summary>
Upload pictures
</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 a 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)
{
("uploaded photos are not well-formed");
}
else if (FI. Length > 2* 1024 * 1024)
{
Picture greater than 2M, reprocessing
}
Else
{
String Savefilepath = Serverpath + DateTime.Now.ToString ("Yyyymmddhhmmss") + fileName;
Try
{
Save pictures to server first
This.fuPhoto.PostedFile.SaveAs (Savefilepath);
Turn into binary
Employee model = new Employee (int. Parse (ID)); ID is EmployeeID, here is the mock field
BOOL flag = UPLOADHELPER.SAVEEMPLOYEEIMG2DB (model, Savefilepath);
}
Catch
{
("Photo upload failed");
}
Finally
{
Finally delete the picture
if (System.IO.File.Exists (Savefilepath))
{
System.IO.File.Delete (Savefilepath);
}
}
}
}
Else
{
("All selected photos to be uploaded");
}
}

(3), remove photos from the database (return format image)
Copy Code code as follows:

UploadHelper.cs
<summary>
Convert binary to picture 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 taken out, it is possible to assign a value directly to a PictureBox image property under WinForm. However, there is no such powerful control on the Web, so the following steps are available.
2, directly in the Web page in the form of streaming display pictures
(1), Generate Picture Stream page (imghelper. aspx)
There is nothing in the design page of this page, the class file is as follows:
Copy Code code 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>
Picture Auxiliary class
</summary>
public partial class ImgHelper:System.Web.UI.Page
{
protected void Page_Load (object sender, EventArgs e)
{
if (!string. IsNullOrEmpty (request["employeeId"))//employee ID to be passed by the page showing the photo
{
int employeeId = Int. Parse (request["employeeId"]);
Employee model =//employeeservice.getemployeebycondition (new employee (EMPLOYEEID)) [0] as employee; Internal functions find an employee without revealing details
Try
{
byte[] byteimg = model. Photo;
Stream stream = new MemoryStream (byteimg);
System.Drawing.Bitmap img = (System.Drawing.Bitmap) System.Drawing.Bitmap.FromStream (stream, false); Convert into bitmap
Response.Buffer = false;
Response.ContentType = "Image/jpg";
Response.AddHeader ("Content-disposition", "attachment;filename=photo.jpg");//photo name called Photo.jpg
Response.BinaryWrite (byteimg);/write binary stream
Response.End ();
}
Catch
{
Response.End ();
}
}
}
}

(2), the page that displays the photo calls Imghelper. aspx
When the page loads, assign a value to the picture control as follows:
Copy Code code as follows:

THIS.IMGPHOTO.IMAGEURL = "/imghelper.aspx?employeeid=" +tmpemployee.id.tostring (); Imgphoto is a picture control

In general, it is very convenient for WinForm to save one, but for WebForm, we need to have a little thought of transformation. It would be better if a cow wrote a control that directly binds an image object like WinForm. The above code test pass, hope to be helpful to 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.