ToBase64String
Sometimes it is helpful to have a text string
representation of a binary file like an image. This text could be stored in a database, or directly on a web page.
With the Convert class
, we have many helpful conversion utility methods. And ToBase64String
helps us convert a byte
array into a string
with base-64 encoding.
To begin, we include the System.IO
namespace—this is for the File.ReadAllBytes
function. The Convert class
is part of the System
namespace, which is part of every VB.NET program.
File.ReadAllBytes
.ToBase64String
function, which receives a byte
array and returns a String
.Imports System.IO Module Module1 Sub Main() ' Step 1: specify the path of the image, and read all bytes from it. Dim image = "programs/adobe.png" Dim data = File.ReadAllBytes(image) ' Step 2: Call Convert.ToBase64String function. Dim result = Convert.ToBase64String(data) Console.WriteLine(result) End Sub End ModuleiVBORw0KGgoAAA ... AABJRU5ErkJggg==
On web pages (HTML documents) we can specify data URIs in the place of external HTTPS links. And the data returned by ToBase64String
works inside these data URIs.
With .NET, we have many powerful features built into our languages, including base-64 encoding. There is no need in VB.NET to use an external library to encode images into text strings.