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.

deep house cleaning Bannockburn ..
In The News:

Expert analysis reveals whether wired Ethernet or wireless Wi-Fi connections are safer for home internet use, plus practical steps to secure your network from attackers.
Australian construction robot Charlotte uses sand, crushed brick and recycled glass to 3D print fireproof, floodproof homes with reduced carbon footprint.
Cybercriminals are using fake invitation emails to trick recipients into downloading malware and stealing personal information and data.
Flying drones could help retailers fight a 93% increase in theft rates as Flock Safety promotes airborne security systems to track suspects and deter crime.
The Fox News Artificial Intelligence Newsletter brings you the latest news on the emerging technology every Saturday, highlighting top stories.
Hacker group Radiant stole data from 8,000 children at Kido nursery chain, demanding ransom and directly contacting parents with intimidation tactics.
As 18 states implement bell-to-bell cell phone bans, creative students use Google Docs, iMessage on MacBooks and Post-It notes to stay connected in class.
A sheriff's captain says deputies often spend hours writing reports between calls, but Axon's AI program, Draft One, helps them save crucial time in the field.
Sora 2, OpenAI's new video-generation app, can create AI-generated videos based on a singular prompt. The results are both mind-blowing and terrifying.
iPhone and Android users can reduce Wi-Fi calling battery drainage through settings adjustments, background app limits and stronger Wi-Fi connections.
Work email scams are becoming harder to detect as criminals use AI and spoofed addresses to trick employees into opening malicious attachments and links.
From her Arizona living room, Christina Chapman ran a covert hub that helped North Korean operatives infiltrate U.S. firms, netting $17 million in stolen salaries.
UC Santa Barbara researchers developed a soft robotic intubation system that achieved 100% success rates for experts and 96% for paramedics with minimal training.
Scammers exploit probate filings to target grieving families with fake fees and debts, Kurt "Cyberguy" Knutsson reports.
Automotive giant Stellantis becomes latest victim of widespread Salesforce breaches affecting companies like Google, Cisco and Adidas this year.
A woman from Washington reunited with her missing Maine Coon cat Louie after 11 days using Love Lost, a free AI-powered pet recovery platform.
Expert cybersecurity tips help Mac owners remove malware infections and strengthen defenses with antivirus software, password managers and system updates.
Meta's AI chatbot training rules bans sexual roleplay with minors and block access to child abuse material as regulators scrutinize its safety measures.
Online banking users face a new threat: web injection scams that overlay fake pop-ups to steal logins. Here’s how to spot them and protect your accounts.
Meta introduced Teen Accounts to Facebook and Messenger while launching a School Partnership Program for U.S. educators to report bullying within 48 hours.
Executive order signed by President Donald Trump tasks Robert F. Kennedy Jr.'s MAHA Commission with using AI to find new cures for childhood cancers.
New FileFix attack tricks Facebook and Instagram users into running malicious PowerShell commands disguised as Meta account maintenance to deploy StealC infostealer.
Step-by-step instructions help users migrate to Windows 11 while preserving emails, contacts, documents, and software licenses during the transition.
Chrome faces its sixth zero-day attack in 2025 as Google patches critical V8 engine flaw CVE-2025-10585 discovered by Threat Analysis Group.
The Hypershell X Ultra exoskeleton features 12 terrain modes and carbon fiber construction to enhance hiking, cycling and outdoor adventures.

A Lesson in HTML

As the owner of a Country Mall and Top Site... Read More

Getting Started with HTML

The basic language of the internet is html. If you... Read More

The Benefits of the New Firefox Browser

You probably heard of the new Firefox browser version 1.0... Read More

MobiTV and Visual Stimulation Imput for Personal Cognitive Performance

Stimulus thru Caffiene or Visual Input?It appears that the Mobi... Read More

Computer Geeks and Garden Gnomes

First and foremost before I begin my ranting it is... Read More

The Advantages of Portable MP3 Players

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

Home Video? Bring it On

So you got yourself a digital camcorder. If you want... Read More

Web Standards

HTTP ProtocolThe web is run on port 80. You are... Read More

Can Movie Theatres Compete with Home HD TV in the Future?

The battle is heating up for market share, home movie... Read More

Build Your Own Computer

I'm eighty-one years old and I bought my first computer... Read More

A Beginners Guide to Avoiding Viruses

"Aaaaaahhhhhh! I've been invaded by a virus!" Getting a virus... Read More

5 Minute Guide to Video Editing for Beginners

Getting started with video editing is very simple you only... Read More

15 Good Programming Habits

1. Before sitting down for coding, you must have formal... Read More

Cisco Certification: A Survival Guide To The Cisco Cable Jungle

One of the most confusing parts of beginning your Cisco... Read More

5 Ways to Speed Up Your PC

No matter how fast your processor and regardless of how... Read More

Cisco CCNA Candidate FAQ

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

Three Things You Can Do to Keep Your Computer Running at Maximum Performance

Although there are many things that can affect the performance... Read More

Taking Advantage of the iPod Experience

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

Faster Browsing Tips

IF WE say that it was mainly because of the... Read More

This Page Cannot Be Displayed ? What to Do When Your Internet Breaks

The DNS (Domain Name System) servers are what your computer... Read More

Is DVD Storage An Attractive Alternative For Your Computer Backup?

If you have a computer for home use or for... Read More

SmartCar Memory Stick for LapTop Transfer Data

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

Classification of Computers

Computers are available in different shapes, sizes and weights, due... Read More

The Best MP3 Players Under $100

You don't have to fork out $250 for a super-diggy-whizbang... Read More

D2X Digital SLRCoolpix 8800 Actually Refers to Two Nikon Cameras

Addressing a D2X Digital SLRCoolpix 8800 search, this article provides... Read More

kitchen deep cleaning Winnetka ..