vb.net 如何在数据库中保存图片框图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26465309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:22:31  来源:igfitidea点击:

How to save a PictureBox Image in DB

vb.net

提问by Sky Scraper

when i try to capture an image to my webcam in VB.NET using Emgu and copy it into another PictureBox in another Form with this code Form23.PictureBox1.Image = New Bitmap(captureImageBox.Image)and try to save it in my database, it doesn't save and an error appears like this Empty path name is not legalbut the picture is there and copied from the webcam PictureBox.

当我尝试使用 Emgu 在 VB.NET 中将图像捕获到我的网络摄像头,并使用此代码将其复制到另一个表单中的另一个 PictureBox 中Form23.PictureBox1.Image = New Bitmap(captureImageBox.Image)并尝试将其保存在我的数据库中时,它没有保存,并且出现这样的错误,Empty path name is not legal但是图片在那里并从网络摄像头 PictureBox 复制。

this is my code in saving the image in database:

这是我将图像保存在数据库中的代码:

Dim a As OpenFileDialog = New OpenFileDialog

SQL = "UPDATE candidate SET photo='" photo=@photo WHERE idn='" & cd & "'"
        Dim sqlCommand As New MySqlCommand
        sqlCommand.Parameters.Add("@photo", MySqlDbType.LongBlob)
        sqlCommand.Parameters("@photo").Value = IO.File.ReadAllBytes(a.FileName)

       With sqlCommand
            .CommandText = SQL
            .Connection = sConnection
            .ExecuteNonQuery()

but if i save an image from OpenFileDialogit saves. why can't it be?hmm is there a problem in my code in copying the Image from PictureBox to another?

但如果我从OpenFileDialog它保存图像保存。为什么不能?嗯,我的代码在将图像从 PictureBox 复制到另一个时有问题吗?

UPDATE

更新

tried this but it doesn't work either:

试过这个,但它也不起作用:

Replaced this:

替换了这个:

sqlCommand.Parameters.Add("@photo", MySqlDbType.LongBlob)
        sqlCommand.Parameters("@photo").Value = IO.File.ReadAllBytes(a.FileName)

       With sqlCommand
            .CommandText = SQL
            .Connection = sConnection
            .ExecuteNonQuery()

with this one:

有了这个:

Dim ms As New IO.MemoryStream()
PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)
Dim data As Byte() = MS.GetBuffer()
Dim p As New MySqlParameter("@photo", MySqlDbType.LongBlob)
p.Value = data
cmd.Parameters.Add(p)
sqlCommand.Parameters.Add("@cd", MySqlDbType.Int32).Value = cd
cmd.ExecuteNonQuery()

回答by ??ssa P?ngj?rdenlarp

Caveat: I have no idea what role the FileDialog plays in all this. Saving an image from a PictureBox to a database does not involve a File or a FileDialog.This address the Title question, not the updates where files and dialogs creep in.

警告:我不知道 FileDialog 在这一切中扮演什么角色。将图片从 PictureBox 保存到数据库不涉及 File 或 FileDialog。这解决了标题问题,而不是文件和对话框潜入的更新。

First, consider notstoring an image, but the name of an archived copy of the filename. You can mangle these as in <id>_<orgfilename>.<ext>if you want to embed the ID to the disk file.

首先,考虑存储图像,而是存储文件名的存档副本的名称。<id>_<orgfilename>.<ext>如果您想将 ID 嵌入到磁盘文件中,您可以修改它们。

To save a picturebox image, it needs to be converted to as byte array. Net includes a type converter for that:

要保存图片框图像,需要将其转换为字节数组。Net 包含一个类型转换器:

Dim imgData As Byte()         ' storage for the img bytes

Dim cvt As New ImageConverter
imgData = CType(cvt.ConvertTo(myImage, GetType(Byte())), Byte())

It works (usually), but it also does boxing back and forth from Object (the CType) and issues with the ImageFormat it selects bug me. Doing it yourself is very simple:

它工作(通常),但它也从对象(CType)来回装箱,并且它选择的 ImageFormat 问题让我感到困惑。自己做很简单:

' this is easily used from a class or converted to an extension
Public Shared Function ImgToByteArray(img As Image, imgFormat As ImageFormat) As Byte()
    Dim tmpData As Byte()
    Using ms As New MemoryStream()
        img.Save(ms, imgFormat)

        tmpData = ms.ToArray
    End Using              ' dispose of memstream
    Return tmpData
End Function

This is pretty much what the TypeConverter does without the boxing, but the code controls the format. Then save the byte array to the db:

这几乎是 TypeConverter 在没有装箱的情况下所做的,但代码控制格式。然后将字节数组保存到数据库:

Dim imgData As Byte()         ' storage for the img bytes
imgData = ImgToByteArray(PictureBox1.Image, ImageFormat.Jpeg)

...
sqlCommand.Parameters("@photo").Value = imgData 

If you want a more generic procedure to save from file orpicturebox, create a procedure which accepts a byte array as a param. The button click for Save PictureBoxImage can convert the image to byte array and pass it, as can the other button working from a file:

如果您想要从文件或图片框保存更通用的过程,请创建一个接受字节数组作为参数的过程。单击 Save PictureBoxImage 按钮可以将图像转换为字节数组并传递它,其他按钮也可以从文件中工作:

Function SaveRecord(ingData As Byte(),...other params...) As Boolean

Note: Do not use GetBuffer. See MSDN MemoryStream.GetBuffer:

注意:不要使用 GetBuffer。请参阅MSDN MemoryStream.GetBuffer

Note that the buffer contains allocated bytes which might be unused. For example, if the string "test" is written into the MemoryStream object, the length of the buffer returned from GetBuffer is 256, not 4, with 252 bytes unused. ...

请注意,缓冲区包含可能未使用的已分配字节。例如,如果将字符串“test”写入 MemoryStream 对象,则 GetBuffer 返回的缓冲区长度为 256,而不是 4,其中 252 个字节未使用。...

On a 968,012 byte file, .ToArrayreturns the proper size, GetBufferreturns 1,719,296 with all elements after 968012 being Null.

在 968,012 字节的文件上,.ToArray返回正确的大小,GetBuffer返回 1,719,296 ,其中968012 之后的所有元素为 Null。



With just a little work you can create a class of image helpers:

只需做一点工作,您就可以创建一类图像助手:

Public Class myImaging

    ' image to byte array from file name
    Public Shared Function ImgToByteArray(imgFile As String, 
                imgFormat As ImageFormat) As Byte()
       ...

    ' the one above
    Public Shared Function ImgToByteArray(img As Image, 
           imgFormat As ImageFormat) As Byte()
       ...

    ' going the other way Bytes() --> Image
    Public Shared Function ImgFromByteArray(b As Byte()) As Image
       ...

    ' shrink img and scale it
    Public Shared Function ImgToThumb(img As Image, maxSize As Size) As Image

End Class

Then it is just: imgData = myImaging.ImgToByteArray(picturebox84.Image)

那么它只是: imgData = myImaging.ImgToByteArray(picturebox84.Image)

回答by Joel Coehoorn

Dim a As OpenFileDialog = New OpenFileDialog
'...

SQL = "UPDATE candidate SET photo= @photo WHERE idn= @cd"
Dim sqlCommand As New MySqlCommand(SQL, sConnection)
sqlCommand.Parameters.Add("@photo", MySqlDbType.LongBlob).Value = IO.File.ReadAllBytes(a.FileName)
sqlCommand.Parameters.Add("@cd", MySqlDbtype.Int32).Value = cd

sConnection.Open()
sqlCommand.ExecuteNonQuery()

回答by Sky Scraper

got the answer!

得到了答案!

Dim cn As New MySqlConnection("server = localhost; user id = root; database = db; password = root")
        Dim sqlQuery As String = "UPDATE candidate SET cpos=@cpos, cparty=@cparty, candidacy='Filed', photo=@photo WHERE idn=@cd"
        Dim sqlcom As New MySqlCommand(sqlQuery, cn)
        Dim ms As New IO.MemoryStream()
        PictureBox1.Image.Save(ms, Imaging.ImageFormat.Jpeg)
        Dim data As Byte() = ms.GetBuffer()
        Dim p As New MySqlParameter("@photo", MySqlDbType.LongBlob)
        p.Value = data
        sqlcom.Parameters.Add(p)
        sqlcom.Parameters.AddWithValue("@cpos", ComboBox1.Text)
        sqlcom.Parameters.AddWithValue("@cparty", TextBox1.Text)
        sqlcom.Parameters.Add("@cd", MySqlDbType.Int32).Value = cd
        cn.Open()
        sqlcom.ExecuteNonQuery()