SoFunction
Updated on 2025-04-08

How to store images into database and read images

There are a lot of information about uploading pictures to the database online, and the commonly used ones are as follows:
There are several ways to store image type data:
1. Convert the image to a binary array (byte[])
Copy the codeThe code is as follows:

byte[] fileData = this.;

2. Convert file to binary array according to path
Copy the codeThe code is as follows:

Code
public byte[] returnbyte(string strpath)
{
// Read the file in binary
    FileStream fsMyfile = new FileStream(strpath, , );
// Create a binary data stream reader, associated with the opened file
    BinaryReader brMyfile = new BinaryReader(fsMyfile);
// Relocate the file pointer to the beginning of the file
    (0, );
   byte[] bytes = (Convert.ToInt32(()));
// Close each object of the above new
    ();
   return bytes;
}

3img type gets binary array
Copy the codeThe code is as follows:

public static byte[] Getbyte(Image img)
{
    MemoryStream stream = new MemoryStream();
    (stream, );
    byte[] mydata = new byte[];
    mydata = ();
    ();
    return mydata;
 }

The way to read image type data and display it on a web page is as follows:
1. Return image type directly
Copy the codeThe code is as follows:

private getImageDataFromOracle()
{
string sql = "select IMGDATA from t_img where imgID=100";
string strconn = ["ConnectionStringForOracle"].ToString();
OracleConnection oraConn = new OracleConnection(strconn);
OracleCommand oraComm = new OracleCommand(sql, oraConn);
();
byte[] fileData = (byte[])();
();
ms = new (fileData);
img = (ms);
return img;
}

2. Use page input to display pictures
Page (Page_Load method)
Copy the codeThe code is as follows:

 protected void Page_Load(object sender, EventArgs e)
{
byte[] b_logoImg = (byte[])dt_channelImg.Rows[0]["LogoImage"]; //Get the byte[] array, here is just an example
 if (b_logoImg.Length > 0)
{
logoImg;
MemoryStream ms = new MemoryStream(b_logoImg);
();
= "image/gif";
(b_logoImg, 0, b_logoImg.Length);
();
}
}

The image path is written as: <img src = "" />