Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save Image to a Database?

Tags:

c#

winforms

I encounter this error when I'm trying to save my image into database.

What am I doing wrong? enter image description here

Here's the design of my table:

enter image description here

I'm using Microsoft Server 2008.

like image 951
yonan2236 Avatar asked Jan 31 '11 15:01

yonan2236


People also ask

Can you save images in a database?

A database gives you the opportunity to store photos and other small images in a database table. You can create such a database table for example when you want to create an online photo album with descriptions of your photos. Storing images in a database table is not recommended.

How can we store images in database?

To insert images into a database, the database must support images. Images are stored in binary in a table cell. The data type for the cell is a binary large object (BLOB), which is a new SQL type in SQL3 for storing binary data.

Can we save images in SQL database?

The IMAGE data type in SQL Server has been used to store the image files. Recently, Microsoft began suggesting using VARBINARY(MAX) instead of IMAGE for storing a large amount of data in a single column since IMAGE will be retired in a future version of MS SQL Server.

How do I store images in SQL database?

Insert one image into SQL Server This table will have an integer (int) id and the image column named img. The data type that we are going to use to store images is the varbinary(max). The INSERT statement inserts the value 1 as the id and then inserts the image named 1. png from the folder img in the c drive.


1 Answers

You have two issues:

  1. The (understandable) confusion about the Image data type in SQL Server. This is actually just a large binary object (a BLOB in common parlance). In order to save an image (or anything else) in this column, you have to first convert it to a byte[], then store that byte array in the column.
  2. You're using the Image data type, which is deprecated. If you have control over this design, change it to use varbinary(MAX). While the Image type is still in SQL Server 2008 R2, it will be removed from future versions at some point.

To get a byte[] representing the image, try this out:

byte[] data;

using(System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
    image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
    data = stream.ToArray();
}

The data variable now contains the binary data of the image, and you can use that as your parameter value. There are additional steps you can take here (saving it in another format like JPEG, for example), but this should at least get you started.

When retrieving the data, it'll also come back as a byte[], so you'll need to turn that into an image again.

byte[] data = ...;

Image image = Image.FromStream(new System.IO.MemoryStream(data));
like image 120
Adam Robinson Avatar answered Oct 25 '22 10:10

Adam Robinson