简体   繁体   中英

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!

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 base64String = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

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
cmd.Parameters.Add(p)
cmd.ExecuteNonQuery()

More exmaples here on loading and saving images to database:

http://www.codeproject.com/Articles/437937/Save-and-Retrieve-Image-from-a-SQL-Server-Database

You are entering text in DB and your db field type is image so you are getting error. If possible then change your db field type to varchar it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM