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


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)