在 C# 中从 Access 数据库存储和检索图像
Posted
技术标签:
【中文标题】在 C# 中从 Access 数据库存储和检索图像【英文标题】:Storing and retrieving images from an Access Database in C# 【发布时间】:2014-05-04 20:40:54 【问题描述】:我是 C# 编程的新手,我正在尝试创建一个软件,允许用户将信息和图片保存到 Ms 访问数据库中。我遵循了 youtube 上的教程并设法存储了我需要的信息和图片,但我似乎无法检索图像并将其显示在图片框中。谁能帮帮我?
我的代码是:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace ConnectionApp
public partial class ClinicaPrivada : Form
OleDbConnection DBConnection = new OleDbConnection();
OleDbDataAdapter DataAdapter;
DataTable LocalDatatable = new DataTable();
int rowPosition = 0;
int rowNumber = 0;
public ClinicaPrivada()
InitializeComponent();
private void Form1_Load(object sender, EventArgs e)
ConnectToDatabase();
public void ConnectToDatabase()
DBConnection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=ClinicaPrivada.mdb";
DataAdapter = new OleDbDataAdapter("Select * From Pacientes", DBConnection);
DataAdapter.Fill(LocalDatatable);
if (LocalDatatable.Rows.Count != 0)
rowPosition = LocalDatatable.Rows.Count;
public void RefreshDBConnection()
if (DBConnection.State.Equals(ConnectionState.Open))
DBConnection.Close();
LocalDatatable.Clear();
ConnectToDatabase();
private void btnBrowse_Click(object sender, EventArgs e)
public byte[] ConvertAndStoreToDB(Image InputImage)
Bitmap BmpImage = new Bitmap(InputImage);
MemoryStream Mystream = new MemoryStream();
BmpImage.Save(Mystream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] ImageAsBytes = Mystream.ToArray();
return ImageAsBytes;
public void StoreToDB(byte[] ImageAsBytes)
string NrDoPaciente;
NrDoPaciente = Convert.ToString(txtNrdoPaciente.Text);
string Empresa;
Empresa = Convert.ToString(txtEmpresa.Text);
string DataDaConsutla;
DataDaConsutla = Convert.ToString(txtDatadaConsulta.Text);
if (DBConnection.State.Equals(ConnectionState.Closed))
DBConnection.Open();
try
MessageBox.Show("Saving Image at index:" + rowPosition.ToString());
OleDbCommand insert = new OleDbCommand("Insert Into Pacientes (NrDoPaciente, Empresa, DatadaConsulta, Document) VALUES('" + NrDoPaciente +"','" + Empresa + "','" + DataDaConsutla + "','" + "Document" + "')" , DBConnection);
OleDbParameter InsertParameter = insert.Parameters.AddWithValue("Docu", SqlDbType.Binary);
int rowsAffected = insert.ExecuteNonQuery();
MessageBox.Show("Data Stored successfully in " + rowsAffected.ToString() + "Row");
rowPosition++;
catch (Exception ex)
MessageBox.Show(ex.Message.ToString());
MessageBox.Show(ex.StackTrace.ToString());
finally
RefreshDBConnection();
private Image ReadImageFromDB()
Image FetchedImg;
if (rowNumber >= 0)
byte[] FetchedImgBytes = (byte[])LocalDatatable.Rows[rowNumber]["Document"];
MemoryStream stream = new MemoryStream(FetchedImgBytes);
FetchedImg = Image.FromStream(stream);
return FetchedImg;
else
MessageBox.Show("There are no Images in the database yet. Please reconnect or add some images.");
return null;
private void btnBrowse_Click_1(object sender, EventArgs e)
if (openFileDialog1.ShowDialog() == DialogResult.OK)
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
private void btnSave_Click_1(object sender, EventArgs e)
StoreToDB(ConvertAndStoreToDB(pictureBox1.Image));
private void btnDisplayAll_Click(object sender, EventArgs e)
RefreshDBConnection();
rowNumber = 0;
pictureBox2.Image = ReadImageFromDB();
btnNext.Enabled = true;
BtnPrevious.Enabled = true;
【问题讨论】:
您似乎有从数据库创建图像的代码。你有错误吗?如果是,您可以粘贴它吗? 与此无关,但我建议您将代码移至 SQL Express(免费)。如果您需要文件但买不起服务器,请尝试 SQL Server Express LocalDB。 【参考方案1】:创建数据表,如: 桌子: Id int,图像 OLE 对象
然后使用此代码插入
//Convert img into bytes
byte[] FileBytes = null;
string imgpath = "PatientsPhotos/" + lbl_patientID.Content.ToString() + ".jpg";
FileStream fs = new FileStream(imgpath,System.IO.FileMode.Open,System.IO.FileAccess.Read);
BinaryReader BR = new BinaryReader(fs);
long allbytes = new FileInfo(imgpath).Length;
FileBytes = BR.ReadBytes((Int32)allbytes);
patient.imagepath = FileBytes;
然后,将“imagepath”插入到图片位置表中
并从表中检索图像路径并转换为如下图像:
ImageSourceConverter imgConv = new ImageSourceConverter();
string path = ("PatientsPhotos/" + this.pt_id + ".jpg");
ImageSource imageSource = (ImageSource)imgConv.ConvertFromString(path);
imgVideo.Source = imageSource;
我认为这可能会对您有所帮助。谢谢
【讨论】:
【参考方案2】:您在内存中的图像可能超出范围。 This question 直接相关,如果我没记错的话。
您必须制作图像的副本。否则,您的图像将链接到创建它的对象,当该对象超出范围时,您的图像数据就会丢失。
我希望您正在尝试执行的操作中遇到异常。
顺便说一句,我同意建议避免使用 MS Access 的评论者。有更好的免费选项可供您使用。
【讨论】:
以上是关于在 C# 中从 Access 数据库存储和检索图像的主要内容,如果未能解决你的问题,请参考以下文章
如何将日期从 C# 存储到 MS-Access 以及如何检索它?
在 Visual Studio C# 中从 MS Access 数据库中获取 OLE(位图)对象,我的代码有啥问题?