使用实体框架6从SQL Server保存并检索图像(二进制) [英] Save and retrieve image (binary) from SQL Server using Entity Framework 6
问题描述
我正在尝试将位图图像保存到数据库
I am trying to save a bitmap image to database
Bitmap map = new Bitmap(pictureBoxMetroMap.Size.Width, pictureBoxMetroMap.Size.Height);
我在数据库中创建了一个列 imgcontent
使用数据类型 binary
但我的问题是如何将这个位图
(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[]));
推荐答案
将图像转换为字节[]
并将其存储在数据库中。
Convert the image to a byte[]
and store that in the database.
将此列添加到您的模型中:
Add this column to your model:
public byte[] Content { get; set; }
然后将您的图像转换为字节数组,并像其他任何数据一样存储: p>
Then convert your image to a byte array and store that like you would any other data:
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
资料来源:将图像转换为字节数组的最快方式
var image = new ImageEntity(){
Content = imageToByteArray(image)
}
_Context.Images.Add(image);
_Context.SaveChanges();
当您想要获取图像时,从数据库中获取字节数组,并使用 byteArrayToImage
,并使用图像执行所需的操作
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
这篇关于使用实体框架6从SQL Server保存并检索图像(二进制)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!