問題描述
我正在嘗試將位圖圖像保存到數(shù)據(jù)庫中
I am trying to save a bitmap image to database
Bitmap map = new Bitmap(pictureBoxMetroMap.Size.Width, pictureBoxMetroMap.Size.Height);
我在數(shù)據(jù)類型 binary
的數(shù)據(jù)庫中創(chuàng)建了一個列 imgcontent
但我的問題是如何將此 bitmap
(map) 轉換為二進制數(shù)據(jù)?
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?
我如何從數(shù)據(jù)庫中檢索數(shù)據(jù)?
And how can I retrieve data from database?
我用谷歌搜索了它,我發(fā)現(xiàn)了類似的東西,但它不起作用:
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[]
并將其存儲在數(shù)據(jù)庫中.
Convert the image to a byte[]
and store that in the database.
將此列添加到您的模型中:
Add this column to your model:
public byte[] Content { get; set; }
然后將您的圖像轉換為字節(jié)數(shù)組并像存儲任何其他數(shù)據(jù)一樣存儲它:
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;
}
}
來源:將圖像轉換為字節(jié)數(shù)組的最快方法
var image = new ImageEntity()
{
Content = ImageToByteArray(image)
};
_context.Images.Add(image);
_context.SaveChanges();
當你想取回圖像時,從數(shù)據(jù)庫中獲取字節(jié)數(shù)組并使用 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模板網(wǎng)!