使用 Entity Framework 6 从 SQL Server 保存和检索图像(二进制)

Save and retrieve image (binary) from SQL Server using Entity Framework 6(使用 Entity Framework 6 从 SQL Server 保存和检索图像(二进制))
本文介绍了使用 Entity Framework 6 从 SQL Server 保存和检索图像(二进制)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

I am trying to save a bitmap image to database

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

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

I created a column imgcontent in the database with datatype binary but my problem is how can I convert this bitmap (map) to binary data?

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

And how can I retrieve data from database?

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

I googled it and I found something like this but it didn't work:

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

推荐答案

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

Convert the image to a byte[] and store that in the database.

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

Add this column to your model:

public byte[] Content { get; set; }

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

Then convert your image to a byte array and store that like you would any other data:

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

来源:将图像转换为字节数组的最快方法

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

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

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

When you want to get the image back, get the byte array from the database and use the ByteArrayToImage and do what you wish with the Image

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

This stops working when the byte[] gets to big. It will work for files under 100Mb

这篇关于使用 Entity Framework 6 从 SQL Server 保存和检索图像(二进制)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)
How to store delegates in a List(如何将代表存储在列表中)
How delegates work (in the background)?(代表如何工作(在后台)?)
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)