Personal Technology Information

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.


MORE RESOURCES:

04/18/2024
We Finally Know Where Neuralink’s Brain Implant Trial Is Happening
After months of secrecy, Neuralink revealed that the partner site for its brain implant study is the Barrow Neurological Institute.


more info


04/18/2024
The Trump Jury Has a Doxing Problem
One juror in former US president Donald Trump’s criminal case in New York has been excused over fears she could be identified. It could get even messier.


more info


04/18/2024
The 33 Best Shows on Max (aka HBO Max) Right Now
From "The Sympathizer" to "Conan O’Brien Must Go," here's everything you need to be watching on Max this month.


more info


04/18/2024
RFK Jr.’s Very Online, Conspiracy-Filled Campaign
Robert F. Kennedy Jr. launched his campaign one year ago this week.


more info


04/18/2024
Far-Right Sheriffs Want a Citizen Army to Stop 'Illegal Immigrant' Voters
Speakers at a conference for Constitutional Sheriffs claimed that militias need to patrol polling stations to stop the "expected flood" of immigrant voters.


more info


04/18/2024
The Best Handheld Gaming Consoles
The second golden age of portable gaming is here! Mostly. These are the top gadgets for taking your video games on the go.


more info


04/18/2024
Tesla’s Layoffs Won’t Solve Its Growing Pains
The car company popularized EVs. Now, facing intense competition from China, it has to figure out what to do next.


more info


04/18/2024
What If Your AI Girlfriend Hated You?
AngryGF offers a perpetually enraged chatbot intended to teach men better communication skills. WIRED took it for a spin.


more info


04/18/2024
The Best Coffee Grinders to Amp Up Your Morning Brew
Get more joy from your java. These conical-burr, flat-burr, and bladed machines let you enjoy freshly ground beans in every cup.


more info


04/18/2024
Gillian Anderson Answers The Web's Most Searched Questions
Gillian Anderson joins WIRED to answer her most searched questions from Google. Why did she lie about her age to be casted for The X Files? How did she get honorary British citizenship? How would she describe her style on Netflix's Sex Education? The actor answers all these questions and more!Director: Justin WolfsonDirector of Photography: Jack BelisleEditor: Louville MooreTalent: Gillian AndersonLine Producer: Joseph BuscemiAssociate Producer: Brandon WhiteProduction Manager: Peter BrunetteProduction and Equipment Manager: Kevin BalashTalent Booker: Jenna Caldwell; Meredith JudkinsCamera Operator: Christopher EustacheSound Mixer: Mike GugginoProduction Assistant: Sonia ButtSet Designer: Jeremy Derbyshire-MylesPost Production Supervisor: Christian OlguinPost Production Coordinator: Ian BryantSupervising Editor: Doug LarsenAssistant Editor: Justin Symonds


more info


04/18/2024
What It Will Take for Airchat to Take Flight
This week, we talk about the buzzy new social media app where there’s no typing allowed.


more info


04/18/2024
Donald Trump Is 'Seriously Considering' Jake Paul's Fight Invite
Influencers like Jake Paul can offer Donald Trump inroads to audiences beyond his base—and prime seats at a major spectacle.


more info


04/18/2024
The Real-Time Deepfake Romance Scams Have Arrived
Watch how smooth-talking scammers known as “Yahoo Boys” use widely available face-swapping tech to carry out elaborate romance scams.


more info


04/18/2024
The Rise of the Carbon Farmer
Farmers around the world are reigniting the less intensive agricultural practices of yesteryear—to improve soil health, raise yields, and trap carbon in the atmosphere back down in the soil.


more info


04/18/2024
Google Fires Twenty-Eight Workers for Protesting Cloud Deal with Israel
The fired workers included nine Google employees who were removed by police after occupying Google offices on Tuesday.


more info


04/17/2024
Delta Is an iOS Game Boy Emulator That (Likely) Won’t Get Taken Down
A new app called Delta that lets iPhone owners play old Nintendo games is available on the App Store. Apple removed a similar emulator Monday.


more info


04/17/2024
The Atlas Robot Is Dead. Long Live the Atlas Robot
Before the dear old model could even power down, Boston Dynamics unleashed a stronger new Atlas robot that can move in ways us puny humans never can.


more info


04/17/2024
Big Tech Says Spy Bill Turns Its Workers Into Informants
One of Silicon Valley’s most influential lobbying arms joins privacy reformers in a fight against the Biden administration–backed expansion of a major US surveillance program.


more info


04/17/2024
Sony TVs Are Getting Brighter in 2024
OLED takes a step back as the brand embraces the brightness wars with some powerful new weapons.


more info


04/17/2024
Will the Olympics Save Nike From Its Midlife Crisis?
Nike’s reputation—and sales—are both in trouble. The Paris games could be the aging brand’s chance to turn its fortunes around.


more info


04/17/2024
Luxury Airbnb High-Rises Are Reshaping Miami’s Skyline
Airbnb is encouraging developers to build condo towers purposefully designed to be listed for short-term rentals. Units are selling fast in Miami and coming soon to other US cities.


more info


04/17/2024
How One Author Pushed the Limits of AI Copyright
Elisa Shupe was initially rebuffed when she tried to copyright a book she wrote with help from ChatGPT. Now the US Copyright Office has changed course—but there’s a catch.


more info


04/17/2024
Hackers Linked to Russia’s Military Claim Credit for Sabotaging US Water Utilities
Cyber Army of Russia Reborn, a group with ties to the Kremlin’s Sandworm unit, is crossing lines even that notorious cyberwarfare unit wouldn’t dare to.


more info


04/17/2024
No, Dubai’s Floods Weren’t Caused by Cloud Seeding
Heavy rain has triggered flash flooding in Dubai. But those who blame cloud seeding are misguided.


more info


04/17/2024
Google Workers Detained by Police for Protesting Cloud Contract With Israel
Videos show nine Google workers being removed by police from offices in New York and Sunnyvale, California, after occupying them in protest against a cloud deal with Israel’s government.


more info



home | site map | contact us