无法在Windows窗体应用程序中显示来自SQL Server数据库的图片框控件中的图像



我想从我的C#Windows窗体应用程序将扫描的图像(车辆文档(添加到SQL Server数据库中。在SQL Server数据库中,保存扫描文档的列的数据类型为Image,我希望将图像存储为每个扫描文档的数组。这是我将数据保存到SQL Server数据库中的代码。

浏览按钮代码:

private void btnBrowseFiles_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "image files|*.jpg;*.png;*.gif;*.icon;*.bmp;*.*";
DialogResult dResult = fileDialog.ShowDialog();
if (dResult == DialogResult.OK)
{
pBoxVehicleDocument.Image = Image.FromFile(fileDialog.FileName);
}
}

添加按钮代码:

private void btnAdd_Click(object sender, EventArgs e)
{
string documentName, vehicleId;
documentName = txtDocumentName.Text;
vehicleId = lblVehicleId.Text;

MemoryStream mStream = new MemoryStream();
pBoxDocument.Image.Save(mStream, System.Drawing.Imaging.ImageFormat.Jpeg);
mStream.ToArray();
//The documentName, vehicleId and imageArray to be passed to AddVehicleDocuments Method within Vehicles Class.
//No I am getting invalid arguments exception on AddVehicleDocuments() method.
Vehicles.AddVehicleDocuments(documentName, vehicleId, imageArray);
}

最后是车辆类别中的AddVehicleDocuments方法代码:

public static void AddVehicleDocuments(string documentName, int vehicleId, byte[] imageString)
{
string query = string.Format("insert into tblDocuments values ('{0}', {1}, {3})", documentName, vehicleId, imageString);
DataAccess.Execute(query);
}

现在,以下代码用于图像选择。我不确定如何将数据库中的数组值转换回Windows窗体上的图片框:

private void childDocumentDetails_Load(object sender, EventArgs e)
{
int documentId = Convert.ToInt32(lblDocumentId.Text);
DataRow dr = Vehicles.GetDocumentDetailsById(documentId);
txtDocumentName.Text = dr["DocumentName"].ToString();
txtVehicleNo.Text = dr["VehicleNo"].ToString();
//here the image array from the database will locate in dr["VehicleDocument"];

pBoxDocument.Image = //Need to write my code here
}

DataRow-dr包含给定文档的所有三个记录,即DocumentName、VehicleNo/VehicleID和字节字符串,但图片框控件仍然不显示目标图像。在这方面只需要一些专家建议。

如有任何帮助,我们将不胜感激。

因为根据我的研究,我确信SQL Server端的图像数据类型可以用于存储车辆的扫描文档。然而,我后来修改了我的代码,并使用Verbinary(MAX(作为在数据库中存储图像的数据类型。

我修改了我的插入代码,现在看起来像这样:

private void btnAdd_Click(object sender, EventArgs e)
{
string documentName, vehicleId;
documentName = txtDocumentName.Text;
vehicleId = lblVehicleId.Text;

MemoryStream mStream = new MemoryStream();
pBoxDocument.Image.Save(mStream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imagesBytes = mStream.ToArray();
Vehicles.AddVehicleDocuments(documentName, vehicleId, imagesBytes);
}

图像选择代码看起来像:

private void childDocumentDetails_Load(object sender, EventArgs e)
{
int documentId = Convert.ToInt32(lblDocumentId.Text);
DataRow dr = Vehicles.GetDocumentDetailsById(documentId);
txtDocumentName.Text = dr["DocumentName"].ToString();
txtVehicleNo.Text = dr["VehicleNo"].ToString();
byte[] imageString = (byte[]dr["VehicleDocument"]);
MemoryStream mStream = new MemoryStream(imageString);
pBoxDocument.Image = Image.FromStream(mStream);
}

感谢@Jimi建议修改代码。

最新更新