Hi I'm trying to save resized image from Picturebox to database. I have this code:
Dim Obrazek As Image
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
Dim NewSize As New Size(773, 580)
ResizeImage = New Bitmap(PictureBox1.Image, NewSize)
PictureBox1.Image = ResizeImage
Obrazek = ResizeImage
Dim ImageIDShop As String = "0000"
'Get Image Via Memory stream
Dim img As Image = Obrazek
Dim ms As New MemoryStream
Dim buffer As Byte() = ms.GetBuffer
'Add SQL Parameters
SQL.QueryArcades("INSERT INTO [dbo].[ImageTable]
You have a great deal going on on that little bit of code:
I would perform each step via an individual method. You also have multiple variables referring the same thing:
ResizeImage all refer to the same image object. If you want to show the original or resized image in a
PictureBox you cannot also Dispose of it. You'll likely get a big red X in it.
' 1: get selected image form user If OpenFileDialog1.ShowDialog <> DialogResult.OK Then Return Dim imgData As Byte() Using selectedImg As Image = Image.FromFile(OpenFileDialog1.FileName) Using imgThumb As New Bitmap(selectedImg.Width \ 2, selectedImg.Height \ 2), g = Graphics.FromImage(imgThumb) ' 2: create resized image g.DrawImage(selectedImg, 0, 0, imgThumb.Width, imgThumb.Height) ' cannot use a Disposed image 'pBox.Image = imgThumb ' 3: convert to byte() Using ms As New MemoryStream() imgThumb.Save(ms, ImageFormat.Jpeg) ' Do NOT use getbuffer! imgData = ms.ToArray() End Using End Using End Using Dim ImageIDShop As String = "0000" ' 4: save to DB Using dbCon As New MySqlConnection(MySQLConnStr), cmd As New MySqlCommand("INSERT INTO BlobDemo (itemName, itemType, imgData) VALUES (@p1, @p2, @p3)", dbCon) cmd.Parameters.Add("@p1", MySqlDbType.String).Value = ImageIDShop cmd.Parameters.Add("@p2", MySqlDbType.String).Value = "jpg" cmd.Parameters.Add("@p3", MySqlDbType.Blob).Value = imgData dbCon.Open() cmd.ExecuteNonQuery() End Using
usingblocks to dispose of those things which should be disposed
GetBuffer()- as noted on MSDN it can result in a byte array much much larger than it needs to be and bloat the DB as a result.
SQL.AddParamis - it looks like some sort of DB "helper". Given the params it almost have to be using
AddWithValuewith is not advised. There is not so much involved that it needs a helper.