简体   繁体   English

将图片从PictureBox保存到数据库

[英]Saving a Image from PictureBox to a database

I was wondering how can I save a picture I choose from my computer using a browse File Dialog to a Database in visual basic. 我想知道如何将使用浏览文件对话框从计算机中选择的图片保存到Visual Basic中的数据库中。

I am using the following code to choose the image form my PC: 我正在使用以下代码从PC上选择图像:

Private Sub btnBuscar_Click(sender As Object, e As EventArgs) Handles btnBuscar.Click

With OpenFileDialog1
    .CheckFileExists = True
    .ShowReadOnly = False
    .Filter = "All Files |*.*| Bitmap Files (*)|*.bmp;*.gif;*.jpg"
    .FilterIndex = 2

    If .ShowDialog = DialogResult.OK Then

        PictureBox1.Image = Image.FromFile(.FileName)

    End If

  End With

End Sub

From my form I am calling another class to create the object: 从我的表单中,我正在调用另一个类来创建对象:

gestor.agregarMission(txtNombre.Text, txtTrip.Text, dtInicio.Value, numDuracionDia.Text, programa, txtDatos.Text, txtResul.Text, picture, txtNave.Text, cuerpo)

I need to construct an object Mission with some parameters including a Image, this is the constructor: 我需要使用一些参数(包括图像)构造对象Mission,这是构造函数:

Public Sub agregarMission(pnombre As String, ptripulantes As String, pfechaLanz As Date, pduracion As Double, pprograma As String, pdescripcion As String, presultado As String, **pinsignia As Image**, pnave As String, pcuerpo As String)

Dim objMision As New Mision(pnombre, ptripulantes, pfechaLanz, pduracion, pprograma, pdescripcion, presultado, pinsignia, pnave, pcuerpo)
multiMision.registrarMission(objMision)

End Sub

What I can't seen to find is the equivalent for pictureBox.Image or wahetever so I can send it to the constructor. 我看不到的是pictureBox.Image或wahetever的等效项,因此我可以将其发送给构造函数。

In my SQL table the field type is Image, I've been told that the Image type is actually an array, so I don't know if I can convert it to String later and recover it later as the original type. 在我的SQL表中,字段类型为Image,有人告诉我Image类型实际上是一个数组,因此我不知道是否可以稍后将其转换为String并在以后恢复为原始类型。

If anyone can give me a tip I would be very grateful! 如果有人可以给我小费,我将不胜感激!

If you pass the Image filename as a string into your agregarMission , you can use it to read the image, convert it to bytes and insert it. 如果将Image文件名作为字符串传递给agregarMission ,则可以使用它读取图像,将其转换为字节并插入。 The PictureBox isn't needed unless you use it for something else. 除非您将PictureBox用于其他用途,否则不需要。

Dim fiImage As FileInfo = New FileInfo(imageFilename)
Dim fs As FileStream = New FileStream(imageFilename, FileMode.Open, FileAccess.Read, FileShare.Read)
Dim imgByteArray = New Byte((Convert.ToInt32(fiImage.Length)) - 1) {}
fs.Read(imgByteArray, 0, Convert.ToInt32(fiImage.Length))
fs.Close

Insert imgByteArray into your table field imgByteArray插入表格字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM