Save and retrieve image (binary) from SQL Server using Entity Framework 6

醉酒当歌 提交于 2019-12-27 11:01:12

问题


I am trying to save a bitmap image to database

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

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[]));

回答1:


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

Source: Fastest way to convert Image to Byte array

var image = new ImageEntity(){
   Content = imageToByteArray(image)
}
_Context.Images.Add(image);
_Context.SaveChanges();

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

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



来源:https://stackoverflow.com/questions/25400555/save-and-retrieve-image-binary-from-sql-server-using-entity-framework-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!