With the following function I can load a picture from file and encode it to base64:
Public Function EncodeFileBase64() (strPicPath As String) As String
Const adTypeBinary = 1 ' Binary file is encoded
' Variables for encoding
Dim objXML
Dim objDocElem
' Variable for reading binary picture
Dim objStream
' Open data stream from picture
Set objStream = CreateObject("ADODB.Stream")
objStream.Type = adTypeBinary
objStream.Open
objStream.LoadFromFile (strPicPath)
' Create XML Document object and root node
' that will contain the data
Set objXML = CreateObject("MSXml2.DOMDocument")
Set objDocElem = objXML.CreateElement("Base64Data")
objDocElem.DataType = "bin.base64"
' Set binary value
objDocElem.nodeTypedValue = objStream.Read()
' Get base64 value
' EncodeFileBase64 = objDocElem.Text
EncodeFileBase64 = Replace(objDocElem.Text, vbLf, "")
' Clean all
Set objXML = Nothing
Set objDocElem = Nothing
Set objStream = Nothing
End Function
As I would like to resize the image before encoding it I guess that the 'logic' should be:
- 1 - Load the image by selecting it using a dialog, resize it and display it into a image.picture
control:
Private Sub CommandButtonImage_Click()
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.ButtonName = "Submit"
.Title = "Selezionare un'immagine"
.Filters.Add "Image", "*.gif; *.jpg; *.jpeg; *.png", 1
If .Show = -1 Then
' file has been selected
' Resize somehow the image
' display preview image in an image control
Me.Image1.PictureSizeMode = fmPictureSizeModeZoom
Me.Image1.Picture = LoadPicture(.SelectedItems(1))
Else
' something
End If
End With
End Sub
- 2 - Get the image data by loading it from the Image Control Me.Image1.Picture
- 3 - Pass the loaded data to the encode_to_base64 function
The problem is that I don't know how to change the ADODB.stream
code above so that it does not loads the picture from a file but it loads the picture from Me.Image1.Picture
and then encodes it to base64. It should be possible as I found something similar here.