我正在尝试将位图图像保存到数据库中
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 保存和检索图像(二进制)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!