How to send an Image(base64) to an API with Visual Basic
If from my last article, I explained how to make an API Call using Visual Basic. Today I will explain how to send an image to an API with Visual Basic.
The common way to send an image to an API is by using base64 encoding. If you don’t know what is base64 encoding is, you can see it here first.
There are so many ways to encode images in base64 format. But in this article, I’m using Visual Basic 6.0 to encode the image.
Without further ado, let’s read the step below.
First You can download the example base64 VB class here.
With that source code, you can try to upload an image. But that base64 class that I’ve downloaded has a “bug” that causes an error when we send an image to an API.
Here’s why?
That class is generating Enter characters or Carriage Return/CR characters causing an error because base64 encoding results are “dirty”. We can use Ms. Word to see these characters
So, the solution is we should remove all CR characters with Replace function on VB6.
Replace(Bas64.Base64Buf, vbCrLf, "")
You can add this code below to my source code that you can download here.
Base64StringImage = """" & Replace(Bas64.Base64Buf, vbCrLf, "") & """"
sEntityBody = "{" + vbCrLf + """reference_id"":99," + vbCrLf
sEntityBody = sEntityBody & """photo_image""" & ":" & Base64StringImage & vbCrLf & "}"
Good luck and hope this will be useful.
Software :
Windows 10 Pro
Ms. Visual Basic 6.0
Labels: API, base64, Visual Basic