How to Save an Image in a SQL Server Database?

Most of the web applications have a lot of images used in it. These images are usually stored in a web server folder and they are accessed by giving the relative path to the file with respect to the root folder of the website. .Net being the platform for distributed application now, ASP.Net can be used to store images that are small to be stored in a database like SQL Server 2000 and later versions. For this purpose the SQL Server database provides a data type called "image" which is used to store images in the database.

To access these images stored in the database we will be using the ADO.Net classes. To find out how to insert and retrieve an image in to the SQL Server database, you can create a .aspx page which can have a HTMLInputFile control which is used to select the image file that is to be saved in the database. You can also create a textbox control in which you can add the image name or some comment or an image id for the image saved. Use a button control to upload the image to the database. Namespaces like System.Data.SqlClient, System.Drawing, System.Data, System.IO, and System.Drawing.Imaging are used in this task.

In the OnClick property of the button you can write the following code to upload an image to the database.

// create a byte[] for the image file that is uploaded
int imagelen = Upload.PostedFile.ContentLength;
byte[] picbyte = new byte[imagelen];
Upload.PostedFile.InputStream.Read (picbyte, 0, imagelen);
// Insert the image and image id into the database
SqlConnection conn = new SqlConnection (@"give the connection string
here...");
try
{
conn.Open ();
SqlCommand cmd = new SqlCommand ("insert into ImageTable "
+ "(ImageField, ImageID) values (@pic, @imageid)",
conn);cmd.Parameters.Add ("@pic", picbyte);
cmd.Parameters.Add ("@imageid", lblImageID.Text);
cmd.ExecuteNonQuery ();
}
finally
{
conn.Close ();
}

You can also write the above code in a function and call that function in the OnClick event of the upload button. The code given above performs the following steps in the process of inserting an image into the database.

1. Get the content length of the image that is to be uploaded
2. Create a byte[] to store the image
3. Read the input stream of the posted file
4. Create a connection object
5. Open the connection object
6. Create a command object
7. Add parameters to the command object
8. Execute the sql command using the ExecuteNonQuery method of the command object
9. Close the connection object

To retrieve the image from the SQL Database you can perform the following steps.

1. Create a MemoryStream object. The code can be something like, MemoryStream mstream = new MemoryStream ();

2. Create a Connection object

3. Open the connection to the database

4. Create a command object to execute the command to retrieve the image

5. Use the command object's ExecuteScalar method to retrieve the image

6. Cast the output of the ExecuteScalar method to that of byte[] byte[] image = (byte[]) command.ExecuteScalar ();

7. Write the stream mstream.Write (image, 0, image.Length);

8. Create a bitmap object to hold the stream Bitmap bitmap = new Bitmap (stream);

9. Set the content type to "image/gif" Response.ContentType = "image/gif";

10. Use the Save method of the bitmap object to output the image to the OutputStream. bitmap.Save (Response.OutputStream, ImageFormat.Gif);

11. Close the connection

12. Close the stream mstream.Close();

Using the above steps you can retrieve and display the image from the database to the web page.

You can use these algorithms and take advantage of the "image" data type available in the SQLServer 2000 database to store small images that correspond to a particular record in the table of the database. This method of storing avoids the tedious task of tracking the path of the web folder if the images are stored in a web folder.

Visit a guide to .net for a complete introduction to .NET framework. Learn about ASP.NET, VB.NET, C# and other related technologies.

Beecher limo rentals ..
In The News:

Safeguarding your digital life with a reliable physical backup isn't just a precaution, it's a necessity. Kurt “CyberGuy" Knutsson provides the essential backup checklist.
Kurt “CyberGuy" Knutsson reveals how a Redditor exposed false recycling claims at their apartment, highlighting a report that only 21% of U.S. recyclables are processed.
Kurt "CyberGuy" Knutsson offers a travel toolkit featuring five technology tools to help you with booking flights and hotels for your summer vacation.
The bubble behind the clock on your iPhone can appear in different colors. Kurt "CyberGuy" Knutsson explains what each of those colors mean.
Scammers are using the power of artificial intelligence to mimic voices of people and are using the fake voices to commit crimes, like kidnappings.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Tech guru Kurt "CyberGuy" Knutsson explains the science behind the Invisibility Shield, a 6-foot shield that makes people become invisible.
The International Olympic Committee on Friday announced plans to use AI in various Olympic aspects, including athlete identification, training and judging.
Tech guru Kurt "CyberGuy" Knutsson explains an easy trick to avoid squinting while working or surfing the web by zooming in on your personal computer.
Streaming giant Roku has recently been targeted by a pair of cyberattacks, and the company confirmed over a half million Roku accounts were compromised.
The Land Aircraft Carrier combines an all-terrain, six-wheeled vehicle with a two-seat aircraft, which features electric vertical takeoff and landing.
The European Union has sent TikTok a "request for information" on the video sharing platform's newest app, TikTok Lite, under the Digital Services Act, with the aim to clean up social media.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
The FBI is warning the public about a recent phishing scam via text that claims its targets owe money in Pennsylvania for unpaid road toll charges.
Your Apple Music settings may be revealing to your contacts what you're listening to. Kurt "CyberGuy" Knutsson explains the process to change those settings.
Learn how to secure social media accounts, implement legacy contacts, and create a digital estate plan to protect your online assets from 'ghost hackers' after your death.
A ported phone number scam is leading to more people having their identities stolen by sophisticated scammers. Kurt “CyberGuy" Knutsson tells you what you need to know.
The Great Pacific Garbage Patch, a vast marine debris vortex, is being tackled by The Ocean Cleanup’s innovative technologies. Kurt “CyberGuy" Knutsson explains.
Discover easy solutions to tame autocorrect frustration on iOS and Android devices. Turn off, customize and add personal touches to your typing experience.
Kurt “CyberGuy" Knutsson reveals the six top things to do right now before it’s too late: Tech and life choices that can keep your safer on and offline.
Kurt “CyberGuy" Knutsson shows you some simple steps to discreetly hide apps or an entire app page on your iPhone for decluttering or confidentiality.
The ambient light sensors on smartphones may be turned into cameras, according to researches at MIT. This could pose a threat to people's privacy.
The Autonomous Road Repair System from tech firm Robotiz3d uses artificial intelligence technology to locate potholes and promptly seal them.
Scammers have stooped to using artificial intelligence to scan obituary websites to create fake obituary websites to target the grieving.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.

Why Get a Microsoft MCSE Certification?

In the years of the dot com boom and bust,... Read More

Learn the Lost Art of Touch Typing

Computers have replaced typewriters, but two-finger, hunt-and-peck typing can never... Read More

Plasma TV vs LCD TV

For those seeking to buy their first flat panel TV... Read More

FTP - File Transfer Protocol Explained

File Transfer Protocol (FTP) is a protocol that is part... Read More

Passwords and the Human Factor

Passwords have a strange dual nature. The stronger and safer... Read More

Why There Are Color Differences in Printing from Your PC

This article describes the basic properties of color, what the... Read More

How to Buy a Plasma Television Set

Most people think that all you have to do to... Read More

Seven Things to Consider When Choosing a PDA

In the early days, Personal Digital Assistants (PDAs) were not... Read More

Taking Advantage of the iPod Experience

Music lovers have been carrying around radios and other bulky... Read More

Cisco CCNA Certification: Five Things To Do DURING The Exam

There are plenty of articles out there about how to... Read More

JVCs First Three-Layer Combo-Disc Blu-Ray / DVD

JVC developed and used a high-performance reflective film to produce... Read More

Cisco CCNA Candidate FAQ

CCNA FAQQ. What exams do I have to take to... Read More

4 Easy Ways to Speed Up A Sluggish PC

Computers are supposed to speed up our productivity?to help us... Read More

Review of Rio MP3 Players

Below you will find some useful information and comments about... Read More

Digital Cameras Ratings Abolish Camera Comparison Guesswork

Digital cameras ratings are great tools for deciding which camera... Read More

Troubleshooting Computer Freeze (Lockup) Problems

How familiar does the following sound? Your computer was working... Read More

Make Windows XP Run Faster!

A friend told me: "My computer startup seems to be... Read More

A Tale of Two Regeds

Tech support tells me to type 'regedt32' as opposed to... Read More

PDA Bible Free Download

Your Bible At Your FingertipsIt is fairly easy to find... Read More

The Advantages of Portable MP3 Players

With their solid-state technology, compact size, and abundant memory, portable... Read More

Be Prepared in the Event Computer Disaster Strikes

ComputersBusinesses and individuals alike have all grown to rely on... Read More

Choosing a Portable MP3 Player: Part 1

MP3 players are everywhere! It seems that the number of... Read More

How To Recognize The Telltale Signs Of Spyware

Spyware is the software that collects information about your online... Read More

SmartCar Memory Stick for LapTop Transfer Data

With the new technology used to transfer information to from... Read More

Flow Text Around a Graphic in Microsoft Word

Flow Text Around a GraphicQuestion: I have inserted a photo... Read More

Bridgeview limo Chicago ..