将图像存储到数据库 blob;从数据库检索到 Picturebox
您好,我之前发布了此内容并获得了一些帮助,但仍然没有有效的解决方案。感谢上次的问答,我已经确定了我的“保存到数据库”代码以及“检索到图片”代码有问题。即使我手动将图片保存在数据库中,它仍然无法检索。这是我根据网络上的 3 或 4 个示例拼凑而成的代码。理想情况下,如果有人有一些已知的良好代码并且可以指导我使用它,那将是最好的。
Dim filename As String = txtName.Text + ".jpg"
Dim FileSize As UInt32
Dim ImageStream As System.IO.MemoryStream
ImageStream = New System.IO.MemoryStream
PbPicture.Image.Save(ImageStream, System.Drawing.Imaging.ImageFormat.Jpeg)
ReDim rawdata(CInt(ImageStream.Length - 1))
ImageStream.Position = 0
ImageStream.Read(rawdata, 0, CInt(ImageStream.Length))
FileSize = ImageStream.Length
Dim query As String = ("insert into actors (actor_pic, filename, filesize) VALUES (?File, ?FileName, ?FileSize)")
cmd = New MySqlCommand(query, conn)
cmd.Parameters.AddWithValue("?FileName", filename)
cmd.Parameters.AddWithValue("?FileSize", FileSize)
cmd.Parameters.AddWithValue("?File", rawData)
cmd.ExecuteNonQuery()
MessageBox.Show("File Inserted into database successfully!", _
"Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
![在此处输入图像描述][1]
'*****使用以下代码检索图片框:
Private Sub GetPicture()
'This retrieves the pictures from a mysql DB and buffers the rawdata into a memorystream
Dim FileSize As UInt32
Dim rawData() As Byte
Dim conn As New MySqlConnection(connStr)
conn.Open()
conn.ChangeDatabase("psdb")
Dim cmd As New MySqlCommand("SELECT actor_pic, filesize, filename FROM actors WHERE actor_name = ?autoid", conn)
Cmd.Parameters.AddWithValue("?autoid", Actor1Box.Text)
Reader = cmd.ExecuteReader
Reader.Read()
'data is in memory
FileSize = Reader.GetUInt32(Reader.GetOrdinal("filesize"))
rawData = New Byte(FileSize) {}
'get the bytes and filesize
Reader.GetBytes(Reader.GetOrdinal("actor_pic"), 0, rawData, 0, FileSize)
Dim ad As New System.IO.MemoryStream(100000)
' Dim bm As New Bitmap
ad.Write(rawData, 0, FileSize)
Dim im As Image = Image.FromStream(ad) * "error occurs here" (see below)
Actor1Pic.Image = im
Reader.Close()
conn.Close()
conn.Dispose()
ad.Dispose()
Hi I posted this earlier and got some help but still no working solution. I have determined thanks to the last q & a that there is something wrong with my "save to db" code as well as my "retrieve to picture" code. Even If I manually save the pic in the db it stil wont retreive. This is code i patched together from 3 or 4 examples around the net. Ideally if someone had some known good code and could direct me to it that would be the best.
Dim filename As String = txtName.Text + ".jpg"
Dim FileSize As UInt32
Dim ImageStream As System.IO.MemoryStream
ImageStream = New System.IO.MemoryStream
PbPicture.Image.Save(ImageStream, System.Drawing.Imaging.ImageFormat.Jpeg)
ReDim rawdata(CInt(ImageStream.Length - 1))
ImageStream.Position = 0
ImageStream.Read(rawdata, 0, CInt(ImageStream.Length))
FileSize = ImageStream.Length
Dim query As String = ("insert into actors (actor_pic, filename, filesize) VALUES (?File, ?FileName, ?FileSize)")
cmd = New MySqlCommand(query, conn)
cmd.Parameters.AddWithValue("?FileName", filename)
cmd.Parameters.AddWithValue("?FileSize", FileSize)
cmd.Parameters.AddWithValue("?File", rawData)
cmd.ExecuteNonQuery()
MessageBox.Show("File Inserted into database successfully!", _
"Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
![enter image description here][1]
'*****retieving to the picturebox using the following code:
Private Sub GetPicture()
'This retrieves the pictures from a mysql DB and buffers the rawdata into a memorystream
Dim FileSize As UInt32
Dim rawData() As Byte
Dim conn As New MySqlConnection(connStr)
conn.Open()
conn.ChangeDatabase("psdb")
Dim cmd As New MySqlCommand("SELECT actor_pic, filesize, filename FROM actors WHERE actor_name = ?autoid", conn)
Cmd.Parameters.AddWithValue("?autoid", Actor1Box.Text)
Reader = cmd.ExecuteReader
Reader.Read()
'data is in memory
FileSize = Reader.GetUInt32(Reader.GetOrdinal("filesize"))
rawData = New Byte(FileSize) {}
'get the bytes and filesize
Reader.GetBytes(Reader.GetOrdinal("actor_pic"), 0, rawData, 0, FileSize)
Dim ad As New System.IO.MemoryStream(100000)
' Dim bm As New Bitmap
ad.Write(rawData, 0, FileSize)
Dim im As Image = Image.FromStream(ad) * "error occurs here" (see below)
Actor1Pic.Image = im
Reader.Close()
conn.Close()
conn.Dispose()
ad.Dispose()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
好吧,自从没有得到帮助后,我就解决了这个问题,并最终让它发挥作用。这是我的工作代码。
从 Picturebox 中保存到 MySQL (pbPicture)
从 MySQL 数据库加载 返回到 Picturebox
注意!只能将一张图片放入图片框中,因此显然此查询只能为您返回一条记录
Well since getting no help i bashed away at the problem and got it to work finally. Here is my working code.
SAVE TO MySQL out of Picturebox (pbPicture)
LOAD from MySQL db Back to Picturebox
NOTE!! can only put one picture in picturebox so obviously this query can only return one record for you
接受和赞成的答案可能有效,但它不是最理想的,而且相当浪费:
MemoryStream
将图像放入字节数组中。.GetBuffer()
是完全不正确的:memstream 缓冲区通常包含未使用的已分配字节。对于 25k 的测试文件,
ToArray()
返回 25434 字节 - 图像的正确大小 - 而GetBuffer()
返回 44416。图像越大,空字节越多将有。它使用 MySQL 提供程序对象,因为它是这样标记的,但使用的数据提供程序(MySQL、SQLServer、OleDB 等)并不重要:它们都工作相同。
如果图像源是 PictureBox,请使用 MemoryStream:
由于图像必须来自某个地方,如果它是文件,这就是您所需要的:
一旦您将图像作为字节,保存:
从数据库加载图像
请注意,必须处理
Bitmaps
和Images
。如果您在用户浏览数据库时重复创建新图像,您的应用程序将会泄漏并最终崩溃。如果您经常来回转换,您可以编写一个帮助程序或扩展方法来将图像转换为字节,反之亦然。DBConnection
和DBCommand
对象也需要被处理。Using
块为我们完成了这个任务。参考资料、资源:
GetConnection
helperThe accepted and upvoted answer may work, but it is suboptimal and quite wasteful:
MemoryStream
to get the image into a byte array..GetBuffer()
is quite incorrect:The memstream buffer will often include unused, allocated bytes. With a 25k test file,
ToArray()
returns 25434 bytes - the correct size of the image - whileGetBuffer()
returns 44416. The larger the image, the more empty bytes there will be.This uses MySQL provider objects since it is so-tagged, but the data provider (MySQL, SQLServer, OleDB etc) used doesnt matter: they all work the same.
In cases where the image source is a PictureBox, use a
MemoryStream
:Since the image had to come from somewhere, if it is a file, this is all you need:
Once you have the image as bytes, to save:
Loading Image from DB
Note that
Bitmaps
andImages
must be disposed of. If you repeatedly create new images as the user browses the database your app will leak and eventually crash. If you convert back and forth a lot, you can write a helper or extension method to convert images to bytes and vice versa.DBConnection
andDBCommand
objects also need to be disposed of. TheUsing
block does this for us.References, Resources:
GetConnection
helper使用 MySQL 和 VB.NET 存储和检索图像的经过测试的代码
Tested Code for Store and Retrieve Images using MySQL and VB.NET
我在使用 @dMo 先生的程序时遇到问题,它向我显示错误“列‘图片’不能为空”
这是我的代码。
PS 我很抱歉发布这个 adndand 答案,我没有足够的声誉来评论这篇文章
I am having problem using mr @dMo 's program its showing me an error "Column 'picture' cannot be null"
here is my code.
P.S. Im sorry for posting this adnand answer I have no enough reputation to comment to this post
下面的代码在表中插入一条车辆信息记录。所选汽车的图像将转换为内存流并以 Varbinary 形式保存到数据库中。
一个函数用于将图像转换为内存流。
以下函数将图像转换为内存流。
下面的代码用于显示数据库中的图像。使用 ID(整数)来显示图像。
界面 - 希望有帮助
The code below inserts a record of vehicle information in a table. The Image of the car selected is converted into memory stream and saved to the Database as Varbinary.
A function is used to convert the image to memory stream.
The following function converts the image into memory stream.
The code below is used to display the image from the database. Use the ID (as an integer) to display the image.
Interface - Hope It Helps