【问题标题】:Save and retrieve image (binary) from SQL Server using Entity Framework 6使用 Entity Framework 6 从 SQL Server 保存和检索图像(二进制)
【发布时间】:2014-10-13 13:33:58
【问题描述】:

我正在尝试将位图图像保存到数据库中

Bitmap map = new Bitmap(pictureBoxMetroMap.Size.Width, pictureBoxMetroMap.Size.Height);

我在数据库中创建了一个数据类型为binary 的列imgcontent,但我的问题是如何将此bitmap(映射)转换为二进制数据?

我如何从数据库中检索数据?

我用谷歌搜索了它,我发现了类似的东西,但它不起作用:

byte[] arr;
ImageConverter converter = new ImageConverter();
arr = (byte[])converter.ConvertTo(map, typeof(byte[]));

【问题讨论】:

  • @JensB 谢谢你,但你没有使用 EF!!我说的对吗?

标签: c# entity-framework bitmap binary


【解决方案1】:

将图像转换为byte[] 并将其存储在数据库中。


将此列添加到您的模型中:

public byte[] Content { get; set; }

然后将您的图像转换为字节数组并像存储任何其他数据一样存储它:

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
    using(var ms = new MemoryStream())
    {
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    
        return ms.ToArray();
    }
}

public Image ByteArrayToImage(byte[] byteArrayIn)
{
     using(var ms = new MemoryStream(byteArrayIn))
     {
         var returnImage = Image.FromStream(ms);

         return returnImage;
     }
}

来源:Fastest way to convert Image to Byte array

var image = new ImageEntity()
{
   Content = ImageToByteArray(image)
};

_context.Images.Add(image);
_context.SaveChanges();

当你想取回图像时,从数据库中获取字节数组并使用ByteArrayToImage 并使用Image 做你想做的事

byte[] 变大时,这将停止工作。它适用于 100Mb 以下的文件

【讨论】:

  • 如果我想保存一个超过 100MB 的文件怎么办?如何调整代码?
  • @bangbang 那么我个人会考虑将文件存储在磁盘上,并将文件的路径保存在数据库中。
  • 但是,如果您仍想将其保存在 DB 中,请使用 varbinary(max)。限制 2GB。
  • @AdeelShekhani 我的问题不是数据库无法存储它,而是 EF 会超时或尝试将其发送到数据库需要很长时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-22
  • 2014-10-04
  • 2017-12-30
  • 2011-01-05
  • 2021-05-04
  • 1970-01-01
  • 2013-06-03
相关资源
最近更新 更多