How to save Image to a Database?
I encounter this error when I'm trying to save my image into databa开发者_如何学JAVAse.
What am I doing wrong?
Here's the design of my table:
I'm using Microsoft Server 2008.
You have two issues:
- 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 abyte[]
, then store that byte array in the column. - You're using the
Image
data type, which is deprecated. If you have control over this design, change it to usevarbinary(MAX)
. While theImage
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));
The error is pretty clear, there is no conversion from a GDI Image object to a byte array (which is what the SQL Server data column type Image really is). You need to convert your Image object into a byte array before adding it as a parameter.
精彩评论