如何保存图片到数据库? [英] How to save Image to a Database?

查看:128
本文介绍了如何保存图片到数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的,当我试图挽救我的形象到数据库中此错误。

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

我在做什么错了?

What am I doing wrong?

下面是我的表的设计:

我使用的是Microsoft Server 2008中。

I'm using Microsoft Server 2008.

推荐答案

您有两个问题:


  1. 有关图像的(可以理解的)混乱数据类型SQL Server中。这其实只是一个大的二进制对象(按照一般的说法中的BLOB)。为了保存图像(或其他)在此列,你必须先将其转换为一个字节[] ,那么该字节数组存储在列。

  2. 您正在使用图片数据类型,它被废弃了。如果你可以控制这个设计,将其更改为使用 VARBINARY(MAX)。而图片类型仍然是在SQL Server 2008 R2,它会从一些点以后的版本中被删除。

  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();
}



数据变量现在包含图像的二进制数据,你可以使用它作为你的参数值。还有你可以采取这里(保存在如JPEG另一种格式,例如)额外的步骤,但至少应该让你开始。

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));

这篇关于如何保存图片到数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆