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.

Rolling Meadows Cadillac Escalade rental .. Lockport Chicago limo O’Hare
In The News:

There are a number of features with AirPods you may or may not know about to take your listening experience to the next level. Kurt the CyberGuy explains.
These 35 Chrome extensions have privacy and security concerns. Tech expert Kurt “CyberGuy" Knutsson says to delete them now.
Tech expert Kurt “CyberGuy" Knutsson says 329,000 mph fusion rocket promises to be fast, disruptive and enable deep-space missions.
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 expert Kurt “CyberGuy" Knutsson says a new autonomous AI is a game changer that also raises privacy risks. Is your data safe?
Tech expert Kurt “CyberGuy" Knutsson says robots and drones are revolutionizing fruit farming with faster picking and smarter handling.
Landmark Admin revises May 2024 cyberattack scope to show twice as many people were affected. Kurt “CyberGuy" Knutsson gives tips to help stay safe from an insurance data breach.
Tech expert Kurt “CyberGuy" Knutsson talks about how Yamaha’s hydrogen outboard motor could revolutionize boating with zero emissions.
Tech expert Kurt “CyberGuy" Knutsson reveals how to memorialize or remove a deceased loved one’s Facebook account and protect their digital legacy from misuse or scams.
Tech expert Kurt “CyberGuy" Knutsson says an Apple Watch saved psychiatrist Amanda Faulkner by detecting deadly leukemia early.
Scammers and fraudsters are increasingly targeting the most vulnerable, especially nursing homes and the personal data of their residents. Kurt the CyberGuy has safety tips.
Infected USB flash drives can spread malware among multiple organizations in ways that can easily bypass traditional security systems.
With a fully automated warehouse system and AI-powered robots, Ocado's Hive picks, packs and delivers grocery store orders in just a few minutes.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Recycling robots are using artificial intelligence to learn how to sort recyclables by recognizing patterns in colors, textures, shapes and logos.
The Reachy 2 robot is designed to be friendly and approachable, inviting natural interaction and is perfect for research, education and experimenting with embodied AI.
Kurt "CyberGuy" Knutsson shares several easy ways to keep your credit cards safe from digital thieves while you're traveling this summer.
Arcturus sets up cameras around the edges of baseball stadiums to capture real-time action and generate a 3D digital clone of the game.
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 CyberGuy explains why healthcare organizations are vulnerable to hackers after there have been a half dozen data breaches this year.
Developed at two California universities, the innovative technology combines brain-computer interfaces with advanced AI to decode neural activity into audible speech.
Microsoft patches 12 critical flaws, but six have already been exploited by criminals. Kurt “CyberGuy" Knutsson says updating your system is only a short-term fix.
Tech expert Kurt “CyberGuy" Knutsson discusses how robots can milk, feed and clean cows on dairy farms, boosting efficiency and comfort.
Tech expert Kurt “CyberGuy" Knutsson says quantum internet ensures unhackable security and redefines online privacy and speed.
Kawasaki's CORLEO is a hydrogen-powered, AI-driven rideable robot. Tech expert Kurt “CyberGuy" Knutsson reports on this new way of thinking about off-road transportation.

How To Have Two (Multiple) Copies Of Windows

Having two operating systems is not as difficult as many... Read More

How To Speed Up Your Aging PC And Make It Healthier Too

With a little tweaking and with proper tools, you can... Read More

Nephrology and Dialysis For a PDA

Saving Lives With A Pocket PCFree medical downloads can be... Read More

Improve PC Performance - 6 Tips You Must Know

Are you frustrated with your PC?Is it feeling sluggish or... Read More

10 Tips to SPEED Up Your PC

1. Let your PC boot up completely before opening any... Read More

Buying A PC Flat Screen Monitor

For six years, my Samsung PC 13.8 inch SyncMaster conventional... Read More

Get Ahead When You Build Your Own Computer

If you've been kicking around the idea of building your... Read More

Plasma TV vs LCD TV

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

How to Protect your PC from Spyware in the Cyber Age

Wouldn't you be shocked to find that your personal sensitive... Read More

Maintain Your Computer ? Keep Your Business Running

Maintaining your computer is extremely important ? especially if you... Read More

Cisco Certification: The Most Important Cisco Study Youll Ever Do

All of us are familiar with the pyramids of Egypt.... Read More

SOBIG.F Virus Promises Ill Be Back

On 21 August 2003 Symantec Security Response upgraded the W32.SOBIG.F... Read More

The Many Benefits of Owning a DVR

Has This Ever Happened To You? OK.. it's Friday night,... Read More

Selecting a Personal Digital Assistant

A Computer in Your HandCarrying around an address book and... Read More

Digital Cameras + Photo Printers = Quality Instant Photographs

In the 1950's and 1960's Polaroid's instant cameras were all... Read More

Portable Technology: Getting to Know the Treo

Up until the recent past, those who wanted to take... Read More

10 Tips to Stay Safe and Secure Online

The Internet can be a dangerous place.While you're enjoying the... Read More

Internet Explorer Shortcuts for Mouse-o-phobes

If you're like me, you occasionally find the ubiquitous mouse... Read More

A Peek Into the Near Future of Electronics Technology

How long do you think DVDs have around? 20 years?... 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

Is Digital Camera Technology Making Film Obsolete?

Perhaps not yet, but the handwriting might be on the... Read More

Bluetooth Technology: Tips for Buying Headsets or Headphones

The technological horizon has always got something new to offer,... Read More

The Best MP3 Players Under $100

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

Keeping the Windows Registry Operational

The registry is where the computer stores information about the... Read More

More Cool Web Tricks

If you ask most people what frustrates them most about... Read More

Des Moines rental limo ..