猿问

使用Entity Framework 6从SQL Server保存和检索图像(二进制)

我正在尝试将位图图像保存到数据库


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

我imgcontent在数据库中创建了具有数据类型的列,binary但我的问题是如何将其bitmap(映射)转换为二进制数据?


以及如何从数据库检索数据?


我用谷歌搜索,发现了类似的东西,但是没有用:


byte[] arr;

ImageConverter converter = new ImageConverter();

arr = (byte[])converter.ConvertTo(map, typeof(byte[]));


茅侃侃
浏览 596回答 1
1回答

慕沐林林

将图像转换为byte[]并将其存储在数据库中。将此列添加到模型中:public byte[] Content { get; set; }然后将图像转换为字节数组,并像存储其他任何数据一样存储它: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和执行所需的操作。Image当byte[]变大时,这将停止工作。适用于100Mb以下的文件
随时随地看视频慕课网APP
我要回答