I want to insert an image into a mysql database using the adodb connection in vb.net 2008.
I am using a select query to insert data into database, here is my code fo
create a table with BLOB
field as follows
CREATE TABLE picture (
ID INTEGER AUTO_INCREMENT,
IMAGE BLOB,
PRIMARY KEY (ID)
);
insert into this table using the following query string:
Dim mstream As New System.IO.MemoryStream()
pic_box_save.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()
mstream.Close()
Try
sql = "INSERT INTO image_in_db(id, image_data) VALUES(@image_id, @image_data)"
sql_command = New MySqlClient.MySqlCommand(sql, sql_connection)
sql_command.Parameters.AddWithValue("@image_id", Nothing)
sql_command.Parameters.AddWithValue("@image_data", arrImage)
sql_command.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
MsgBox("Image has been saved.")
Regardless of what data access technology or database you use, you need to convert am Image
to a Byte
first and then save that. On retrieval, you convert the Byte
array back to an Image
.
To save:
Dim connection As New SqlConnection("connection string here")
Dim command As New SqlCommand("UPDATE MyTable SET Picture = @Picture WHERE ID = 1", connection)
'Create an Image object.'
Using picture As Image = Image.FromFile("file path here")
'Create an empty stream in memory.'
Using stream As New IO.MemoryStream
'Fill the stream with the binary data from the Image.'
picture.Save(stream, Imaging.ImageFormat.Jpeg)
'Get an array of Bytes from the stream and assign to the parameter.'
command.Parameters.Add("@Picture", SqlDbType.VarBinary).Value = stream.GetBuffer()
End Using
End Using
connection.Open()
command.ExecuteNonQuery()
connection.Close()
To retrieve:
Dim connection As New SqlConnection("connection string here")
Dim command As New SqlCommand("SELECT Picture FROM MyTable WHERE ID = 1", connection)
connection.Open()
Dim pictureData As Byte() = DirectCast(command.ExecuteScalar(), Byte())
connection.Close()
Dim picture As Image = Nothing
'Create a stream in memory containing the bytes that comprise the image.'
Using stream As New IO.MemoryStream(pictureData)
'Read the stream and create an Image object from the data.'
picture = Image.FromStream(stream)
End Using
That example is for ADO.NET and SQL Server but the principle of using a MemoryStream
for the conversion is the same regardless.