Base 64 strings are actually more common than one would realize. Today, you will learn what Base 64 strings are and how to make use of them properly in your Visual Basic programs.
Base 64 Strings
Base 64 encoding is simply a way of taking data in binary format and turning it into text so that it's easily transmitted. Base 64 is a textual encoding of binary data where the resulting text has nothing but letters, numbers, and symbols; examples are '+', '/', and '='. Base 64 is a very convenient way to store and transmit binary data over media that is specifically used for textual data.
When you have binary data that you need to send across a network, you shouldn't do it by streaming the bits and bytes over the wire in a raw format. This is because some media are specifically made for streaming text. Some protocols may interpret your binary data as control characters (such as a modem), or your binary data could get screwed up because the underlying protocol might think that you have entered a special character combination.
You should encode the binary data into characters. With Base 64, you can rely on the same 64 characters being present in different character sets, and you can be confident that your data is going to end up on the other side of the wire uncorrupted. Base 64 is a way of encoding arbitrary binary data into ASCII text.
Base 64 takes 4 characters per 3 bytes of data, plus potentially a bit of padding at the end. Each 6 bits of the input is encoded in a 64-character alphabet. The 'standard' alphabet uses A-Z, a-z, 0-9, and + and /, with = as a padding character.
The premise is as follows:
Obtain a signature on a portable device which was stored inside an SQL database and display the signature inside a form's picturebox.
Imagine you get a delivery from a courier company. In some cases, the courier might ask you to sign on his/her device that you have received your parcel. This signature usually gets stored inside a database in Base 64 format. Imagine further that you need a copy of the signed proof of delivery. In this case, the signature that was stored needs to be interpreted and displayed inside a picturebox that would form part of a printed report. All of this happens through Base 64 encoding. Your signature gets stored as a Base 64 string that can be read into a picturebox.
The fact that I am making use of a database in this article is to give you a decent example, but this may be optional for some.
Open Visual Studio and create a new Visual Basic Windows Forms project. Add a picturebox onto the form. Make it nice and big and set its WHAT property to Stretch?. Also, include a background color because some images may not be displayed at all because of transparency settings.
To get the signature (or any data that was stored as Base 64), you would write a stored procedure such as the following and make use of this stored procedure in Visual Basic. I will show you this shortly.
Create the following Stored Procedure:
CREATE PROC [dbo].[spSignature] @Key INT, @Signature VARCHAR(MAX) OUTPUT AS BEGIN SET @Signature = (SELECT [SignatureField] FROM TABLE WHERE Key = @Key) END
This simply selects the 'Signature' field from the database.
In Visual Basic, make use of this Stored procedure like this:
Add the Namespaces:
Imports System.Data.SqlClient Imports System.IO
Add the GetSign Function procedure:
Public strSQL As String = "Data Source=DBSOURCE; _ Initial Catalog=DATABASE;Persist Security Info=True; _ User ID=ID;Password=PASSWORD" Public Function getSign(Key As Integer) As String Dim strCon As New SqlConnection(strSQL) Dim strComm As New SqlCommand("spSignature", strCon) strComm.CommandType = CommandType.StoredProcedure strComm.CommandTimeout = 6000 strComm.Parameters.AddWithValue("@Key", Key) Dim parSig As New SqlParameter _ ("@Signature", SqlDbType.VarChar, -1) ' -1 = VARCHAR MAX;' parSig.Direction = ParameterDirection.Output strComm.Parameters.Add(parSig) strCon.Open() strComm.ExecuteNonQuery() Dim strSig As String = (parSig.Value.ToString()) Return strSig End Function
This function calls the Stored Procedure from the database. You also will notice that I have added a parameter named Signature. Because of the unknown size, I have ensured that the Signature field is created as VARCHAR(MAX). Sending -1 through to the parameter from Visual Basic ultimately means the same thing.
Add the Form_Load sub procedure that will obtain the signature and do all the image manipulation for us to get the signature displayed inside the picturebox.
Private Sub Form1_Load(sender As Object, e As EventArgs) Dim strBase64 As String = getSign(30) If Not String.IsNullOrEmpty(strBase64) Then Dim strSign As String = strBase64.Replace _ ("data:image/png;base64,", "") Dim img As Image = ImageFromByteArray _ (Convert.FromBase64String(strSign)) PictureBox1.Image = SwicthColors(img) End If End Sub
Add the ImageFromByteArray function that reads the given memory stream and translates it into an in-memory image:
Public Function ImageFromByteArray(btImage As Byte()) As Image Dim msStream As New MemoryStream(btImage) Dim imgImage As Image = Image.FromStream(msStream) Return imgImage End Function
Lastly, add the SwicthColors procedure. This procedure is responsible for swapping the image's colors around. Usually, the signature from a PDA device gets stored transparently, which makes it difficult to see the image. If we didn't include the next sub, the signature will get displayed, but we will not be able to see it because it will be the same color as the PictureBox's backcolor. This is why we need to invert the image so that we can see the actual image.
Public Function SwicthColors(imgSource As Image) As Bitmap Dim bmpSource As Bitmap = DirectCast(imgSource, Bitmap) Dim bmpClone As Bitmap = DirectCast(bmpSource.Clone(), Bitmap) Dim colPixel As Color For i As Integer = 0 To bmpClone.Width - 1 For j As Integer = 0 To bmpClone.Height - 1 colPixel = bmpClone.GetPixel(i, j) bmpClone.SetPixel(i, j, Color.FromArgb(255 - _ colPixel.R, 255 - colPixel.G, 255 - colPixel.B)) Next Next Dim bmpResult As Bitmap = DirectCast(bmpClone.Clone(), Bitmap) Return bmpResult End Function
Technology is wonderful; embrace it! It is amazing how easy it is to translate Base 64 strings into images.