Binary read/write operations

Source: Internet
Author: User

In software development, we spend a considerable amount of time displaying images in the UI. Generally, developers store images in an image folder and display them as required. To do this, we need to store the image path in the database, and the real image file is stored in a folder. In this way, we can effectively reduce the size of the database, but this will cause a large amount of disk space to be occupied by image files and make these images accessible easily.

Let's look at a solution. In the code to be introduced next, we will know how to store an image file directly to a database instead of a folder on the disk. Some solutions use. NET and sqlserver databases, so that you can use stored procedures.

Summary
From this code, we will know how to store an image file to a database instead of a folder's physical path.
The development environment is tested in vs2005 (website); The database uses sqlserver
Vs2005 (C #, website) + sqlserver

// Save to database
Protected void btnsave_click (Object sender, eventargs E)
{
// Upload the image file to the image
System. Drawing. Image IMG = system. Drawing. image. fromfile (fileimg. postedfile. filename );

// Save it to memory in JPEG format
System. Io. memorystream MS = new system. Io. memorystream ();
IMG. Save (MS, system. Drawing. imaging. imageformat. JPEG );

Using (sqlconnection con = new sqlconnection ("Server =.; database = test; uid = sa ;"))
{
Sqlcommand cmd = new sqlcommand ("spinsertimage", con );
Cmd. commandtype = commandtype. storedprocedure;

Cmd. Parameters. Add ("@ imagebinary", system. Data. sqldbtype. Image );
// Binary data of the image
Cmd. Parameters ["@ imagebinary"]. value = Ms. toarray ();

Con. open ();
Try
{
// Tune the Stored Procedure
Cmd. executenonquery ();
Response. Write ("OK ");
}
Catch
{
Response. Write ("error ");
}
}

IMG. Dispose ();
Ms. Dispose ();
Ms. Flush ();

}
Analysis
The above code is actually to insert the image file into the database. Next I will explain it.

You can see that the initial value of the variable "sinsertquery" is "insert into images ([Image]) values (?).",
This is because we cannot know the complete query statement. We need to add a binary parameter. The value of this parameter is the value after the image file is converted to binary.
(Obviously, this parameter cannot be added to this variable)
For this reason, we use a placeholder [?], It will be replaced by the "queryparameter" parameter.
We use FSO to create a binary olddb parameter.
After this parameter is successfully created, the value is [?]. This parameter will be replaced and executed.

// Read
Public void initdata ()
{
// Bind the image ID in the database to a dropdownlist
Using (sqlconnection con = new sqlconnection ("Server =.; database = test; uid = sa ;"))
{
Sqldataadapter SDA = new sqldataadapter ("spselectimage", con );

Dataset DS = new dataset ();

SDA. Fill (DS );

Ddlimage. datasource = Ds;
Ddlimage. datatextfield = "imageid ";
Ddlimage. datavaluefield = "imageid ";
Ddlimage. databind ();

Ddlimage. Items. insert (0, new listitem ("", "0 "));

SDA. Dispose ();
}
}

Protected void ddlimage_selectedindexchanged (Object sender, eventargs E)
{
Using (sqlconnection con = new sqlconnection ("Server =.; database = test; uid = sa ;"))
{
Sqlcommand cmd = new sqlcommand ("spselectimagebyid", con );
Cmd. commandtype = commandtype. storedprocedure;

Cmd. Parameters. Add ("@ imageid", sqldbtype. INT );
// The imageid selected in the dropdownlist
Cmd. Parameters ["@ imageid"]. value = int32.parse (ddlimage. selectedvalue );

Con. open ();
Sqldatareader SDR = cmd. executereader ();

Response. clearcontent ();
Response. contenttype = "image/JPEG ";
While (SDR. Read ())
{
// Read the binary of the corresponding record and display it
Response. binarywrite (byte []) SDR [1]);
}

SDR. Close ();
SDR. Dispose ();
}

}

The above Code actually reads binary data from the database and displays it as an image in the picture box of the UI. Next we will discuss the above lines of code.
First, import the system. Io namespace to use memorystream.
The "connection ()" here is a user-defined class that contains a public function "dodbconnection ()".
After obtaining the parameter and database name, this public function executes and returns the result.

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.