Asp.net method of storing and reading images into a database

  • 2020-06-19 10:08:08
  • OfStack

There are a lot of materials about ES0en. NET uploading pictures to the database on the Internet. The commonly used ones are as follows:
There are several ways to store image type data:
1. Convert image to base 2 array (byte[])

byte[] fileData = this.FileUpload1.FileBytes; 

2. Converts the file to a base 2 array based on the path

 code  
public byte[] returnbyte(string strpath)
{
 //  In order to 2 Read files in base mode 
    FileStream fsMyfile = new FileStream(strpath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
//  create 1 a 2 Base data stream reader, associated with an open file 
    BinaryReader brMyfile = new BinaryReader(fsMyfile);
//  Relocates the file pointer to the beginning of the file 
    brMyfile.BaseStream.Seek(0, SeekOrigin.Begin);
   byte[] bytes = brMyfile.ReadBytes(Convert.ToInt32(fsMyfile.Length.ToString()));
//  Shut down more than new Each of the objects 
    brMyfile.Close();
   return bytes;
}

Type 3img gets a base 2 array

public static byte[] Getbyte(Image img)
{
    MemoryStream stream = new MemoryStream();
    img.Save(stream, ImageFormat.Jpeg);
    byte[] mydata = new byte[stream.Length];
    mydata = stream.ToArray();
    stream.Close();
    return mydata;
 }

The image type of data is read and displayed on the web page as follows:
1. Returns the image type directly

private System.Drawing.Image getImageDataFromOracle() 
{ 
string sql = "select IMGDATA from t_img where imgID=100"; 
string strconn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringForOracle"].ToString(); 
OracleConnection oraConn = new OracleConnection(strconn); 
OracleCommand oraComm = new OracleCommand(sql, oraConn); 
oraConn.Open(); 
byte[] fileData = (byte[])oraComm.ExecuteScalar(); 
oraConn.Close(); 
System.IO.MemoryStream ms = new System.IO.MemoryStream(fileData); 
System.Drawing.Image img = System.Drawing.Image.FromStream(ms); 
return img; 
} 

2. Use page input to display pictures
Page ES22en. aspx (Page_Load method)

 protected void Page_Load(object sender, EventArgs e)
{
  byte[] b_logoImg = (byte[])dt_channelImg.Rows[0]["LogoImage"]; // get byte[]  Arrays, just to give you an example 
   if (b_logoImg.Length > 0)
   {
    System.Drawing.Image logoImg;
    MemoryStream ms = new MemoryStream(b_logoImg);
    Response.Clear();
    Response.ContentType = "image/gif";
    Response.OutputStream.Write(b_logoImg, 0, b_logoImg.Length);
    Response.End();
  }
}

The path of the picture is written as: < img src = "ImageShow.aspx" / >

Related articles: