Dale Dale - 1 year ago 176
Vb.net Question

Convert data:image/png;base64 into an image type in database

So here is the scenario. I have a canvas and I am getting its data via

var image = canvas.toDataURL("image/png");

and i will put the data into a TextArea so i could insert it into database

document.getElementById("TextArea1").textContent = image

If i will insert the data inside the textarea, the "data:image/png;base64,iVBORw0KGgoAAAAN..." into the database, it says that

Operand type clash: nvarchar(max) is incompatible with image.

So, i what i want and what i need to do is to convert the "data:image/png;base64,iVBORw0KGgoAAAAN..." into something like "0x89504E470D0A1A0A..." when inserting it into database. thanks in advance!

Answer Source

Your image is in Base64 format which is a string, you need to convert that first to a byte array in order to save it in your database. Something like this:


Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Temp\Database1.mdf;Integrated Security=True;User Instance=True")
Dim sql As String = "INSERT INTO MyTable VALUES(@Image)"
Dim cmd As New SqlCommand(sql, con)
Dim imageBytes As Byte() = Convert.FromBase64String(base64String)
Dim p As New SqlParameter("@Image", SqlDbType.Image)
p.Value = imageBytes

More exmaples here on loading and saving images to database:


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download