Skip to content

cImage - Image Data Conversion Class

Overview

cImage provides mutual conversion functionality between Byte()Base64StdPicture image data formats, using a chained call design that allows complex conversions in a single line of code.

Accessible directly through the VBMAN.Image global static instance without manual instantiation.

Core Features

  • Chained Calls: Fluent API design, one line to complete conversion + output
  • Three-Format Conversion: Free conversion between byte arrays, Base64 strings, and StdPicture objects
  • Data URI Support: Automatically parses data:image/jpeg;base64,... format
  • MIME Type Detection: Automatically identifies JPEG/PNG/GIF/BMP/WebP/ICO via file magic numbers
  • Direct Control Assignment: ShowTo method directly displays images to Image/PictureBox controls
  • Default Member: Data method is the default member, supporting VBMAN.Image.(base64Str) shorthand

Usage Patterns

vb
' Global static instance (recommended)
VBMAN.Image.Data(base64Str).ReturnPicture

' Shorthand (using default member)
VBMAN.Image.(base64Str).ReturnPicture

' Independent instance
Dim img As New cImage
Set Image1.Picture = img.Data(bytesArr).ReturnPicture

Method Overview

Chained Entry Method

MethodDescriptionReturn
DataSet data source (default member)cImage (Me)

Chained Helper Methods

MethodDescriptionReturn
SetMimeTypeManually set MIME typecImage (Me)
ShowToDisplay image to target controlcImage (Me)

Output Methods (Terminal Methods)

MethodDescriptionReturn
ReturnBytesOutput as byte arrayByte()
ReturnBase64Output as Base64 stringString
ReturnPictureOutput as StdPicture objectStdPicture
ReturnDataUriOutput as Data URI stringString
ReturnMimeTypeReturn detected MIME typeString

Check Method

MethodDescriptionReturn
IsValidCheck if data is validBoolean

Method Details

Data

Chained call entry point, accepts three data types. Default member, supports shorthand VBMAN.Image.(data).

vb
Public Function Data(ByVal vData As Variant) As cImage

Parameters:

ParameterTypeDescription
vDataVariantData source, supports Byte() array, Base64 string, StdPicture object

Supported Input Types:

TypeDetection BasisExample
Byte() arrayVarType = vbArray Or vbByteByte data from reading an image file
Base64 stringVarType = vbStringAvatar Base64 returned by API
Data URI stringStarts with data:data:image/png;base64,...
StdPicture objectIsObject(vData)Image1.Picture

Data URI Auto-Parsing:

When a data:image/jpeg;base64,xxxxx format string is passed, the MIME type is automatically extracted and the prefix stripped, keeping only the pure Base64 portion.

Return: cImage (Me), supports chained calls

Example:

vb
' From Base64 string
VBMAN.Image.Data("/9j/4AAQ...").ReturnPicture

' From byte array
Dim bytes() As Byte
bytes = VBMAN.FileEx.OpenFile("photo.jpg", "R").ReadData.ReturnBytes
VBMAN.FileEx.CloseFile
VBMAN.Image.Data(bytes).ReturnBase64

' From StdPicture
VBMAN.Image.Data(Image1.Picture).ReturnBase64

' Shorthand (using default member)
VBMAN.Image.("/9j/4AAQ...").ReturnPicture

' Data URI format auto-parsing
VBMAN.Image.("data:image/png;base64,iVBOR...").ReturnPicture

SetMimeType

Manually set MIME type to override auto-detection results or supplement undetectable formats.

vb
Public Function SetMimeType(ByVal MimeType As String) As cImage

Parameters:

ParameterTypeDescription
MimeTypeStringMIME type, e.g., "image/jpeg", "image/png"

Return: cImage (Me), supports chained calls

Example:

vb
' Manually specify MIME type (affects ReturnDataUri output)
VBMAN.Image.Data(bytes).SetMimeType("image/png").ReturnDataUri

' From StdPicture, cannot auto-detect format, need manual specification
VBMAN.Image.Data(Image1.Picture).SetMimeType("image/bmp").ReturnDataUri

ShowTo

Directly display image to the target control, the most convenient display method.

vb
Public Function ShowTo(ByVal Target As Object) As cImage

Parameters:

ParameterTypeDescription
TargetObjectAny control object with a Picture property (Image, PictureBox, etc.)

Return: cImage (Me), supports chained calls

Example:

vb
' Traditional approach - requires Set keyword
Set Image1.Picture = VBMAN.Image.Data(base64Str).ReturnPicture

' Shorthand - one line
VBMAN.Image.(base64Str).ShowTo Image1

' Chain display then get Base64
Dim b64 As String
b64 = VBMAN.Image.(base64Str).ShowTo(Image1).ReturnBase64

' Display to PictureBox
VBMAN.Image.(bytesArr).ShowTo Picture1

' From StdPicture display to another control
VBMAN.Image.Data(Picture1.Picture).ShowTo Image2

ReturnBytes

Convert image data to byte array output.

vb
Public Function ReturnBytes() As Byte()

Return: Byte() byte array

Example:

vb
' Base64 → byte array
Dim bytes() As Byte
bytes = VBMAN.Image.Data(base64Str).ReturnBytes

' StdPicture → byte array (can be used to save image)
Dim picBytes() As Byte
picBytes = VBMAN.Image.Data(Image1.Picture).ReturnBytes

' Write byte array to file
VBMAN.FileEx.SetBufferBytes(bytes).SaveData "C:\output.jpg"

ReturnBase64

Convert image data to Base64 string output.

vb
Public Function ReturnBase64() As String

Return: String - Pure Base64 string (without data: prefix)

Example:

vb
' Byte array → Base64
Dim b64 As String
b64 = VBMAN.Image.Data(bytes).ReturnBase64

' StdPicture → Base64
Dim picB64 As String
picB64 = VBMAN.Image.Data(Image1.Picture).ReturnBase64

' For API request
Dim json As New cJson
json("avatar") = VBMAN.Image.Data(Image1.Picture).ReturnBase64
Dim resp As String
resp = VBMAN.HttpClient.SetUrl("/api/upload").SetBody(json.Encode).Post

ReturnPicture

Convert image data to StdPicture object output, can be directly assigned to control's Picture property.

vb
Public Function ReturnPicture() As StdPicture

Return: StdPicture object

Example:

vb
' Base64 → StdPicture
Set Image1.Picture = VBMAN.Image.Data(base64Str).ReturnPicture

' Byte array → StdPicture
Set Image1.Picture = VBMAN.Image.Data(bytes).ReturnPicture

' Data URI → StdPicture
Set Image1.Picture = VBMAN.Image.("data:image/png;base64,iVBOR...").ReturnPicture

ReturnDataUri

Convert image data to Data URI format string output, suitable for direct embedding in HTML/CSS.

vb
Public Function ReturnDataUri(Optional ByVal MimeType As String) As String

Parameters:

ParameterTypeRequiredDescription
MimeTypeStringNoMIME type. When omitted, uses auto-detection or defaults to image/jpeg

Return: String - Data URI format string, e.g., data:image/png;base64,iVBORw0KGgo...

Example:

vb
' Auto-detect MIME type
Dim uri As String
uri = VBMAN.Image.Data(bytes).ReturnDataUri
' Output: data:image/jpeg;base64,/9j/4AAQ...

' Manually specify MIME type
uri = VBMAN.Image.Data(bytes).SetMimeType("image/png").ReturnDataUri
' Output: data:image/png;base64,iVBORw0KGgo...

' Embed in HTML
Dim html As String
html = "<img src='" & VBMAN.Image.Data(bytes).ReturnDataUri & "'>"
WebBrowser1.Document.Write html

' Generate Data URI from Base64
uri = VBMAN.Image.Data(base64Str).ReturnDataUri("image/png")

ReturnMimeType

Returns the auto-detected image MIME type.

vb
Public Function ReturnMimeType() As String

Return: String - MIME type string

Supported Detection Formats:

FormatMagic Number (Hex)MIME Type
JPEGFF D8 FFimage/jpeg
PNG89 50 4E 47image/png
GIF47 49 46image/gif
BMP42 4Dimage/bmp
WebP52 49 46 46 ... 57 45 42 50image/webp
ICO00 00 01 00image/x-icon

Example:

vb
' Detect image type
Dim mime As String
mime = VBMAN.Image.Data(bytes).ReturnMimeType
Debug.Print mime  ' Output: image/png

' Process based on type
Select Case mime
    Case "image/jpeg"
        ' JPEG processing logic
    Case "image/png"
        ' PNG processing logic
    Case Else
        ' Other formats
End Select

IsValid

Check if the data source is valid (whether data has been set via the Data method).

vb
Public Function IsValid() As Boolean

Return: Boolean - Returns True when data is valid

Example:

vb
Dim img As New cImage
img.Data(base64Str)

If img.IsValid Then
    Set Image1.Picture = img.ReturnPicture
Else
    MsgBox "Image data is invalid!"
End If

Comprehensive Examples

Example 1: API Avatar Display

Get user avatar Base64 from API and display directly to Image control:

vb
Private Sub LoadUserAvatar(userId As Long)
    ' Get avatar Base64 from API
    Dim resp As String
    resp = VBMAN.HttpClient.SetUrl("/api/user/" & userId & "/avatar").Get
    
    ' Parse JSON to get avatar field
    Dim json As cJson
    Set json = VBMAN.Json.Decode(resp)
    Dim avatarB64 As String
    avatarB64 = json("avatar")
    
    ' Display to Image control (one line)
    VBMAN.Image.(avatarB64).ShowTo Image1
End Sub

Example 2: Image Upload to Server

Convert local image to Base64 and upload to API:

vb
Private Sub UploadImage(filePath As String)
    ' Read image file as byte array
    VBMAN.FileEx.OpenFile filePath, "R"
    Dim bytes() As Byte
    bytes = VBMAN.FileEx.ReadData.ReturnBytes
    VBMAN.FileEx.CloseFile
    
    ' Convert to Base64 and detect type
    Dim img As cImage
    Set img = VBMAN.Image.Data(bytes)
    Dim b64 As String
    b64 = img.ReturnBase64
    Dim mime As String
    mime = img.ReturnMimeType
    
    ' Build request JSON
    Dim json As New cJson
    json("image") = b64
    json("mime_type") = mime
    
    ' Upload
    Dim resp As String
    resp = VBMAN.HttpClient _
        .SetUrl("/api/upload") _
        .SetBody(json.Encode) _
        .Post
End Sub

Example 3: Image Data URI Embedding in HTML

Convert image to Data URI and embed in WebBrowser page:

vb
Private Sub ShowEmbeddedImage(filePath As String)
    ' Read image
    VBMAN.FileEx.OpenFile filePath, "R"
    Dim bytes() As Byte
    bytes = VBMAN.FileEx.ReadData.ReturnBytes
    VBMAN.FileEx.CloseFile
    
    ' Get Data URI
    Dim dataUri As String
    dataUri = VBMAN.Image.Data(bytes).ReturnDataUri
    
    ' Embed in HTML
    Dim html As String
    html = "<html><body>" & _
           "<img src='" & dataUri & "' style='max-width:300px'>" & _
           "</body></html>"
    WebBrowser1.Document.Write html
End Sub

Example 4: Full Image Format Conversion Flow

Complete demonstration of conversion between the three formats:

vb
Private Sub TestImageConversion()
    Dim img As cImage
    
    ' 1. Byte array → Base64 + StdPicture + Data URI
    Dim bytes() As Byte
    bytes = VBMAN.FileEx.OpenFile("C:\photo.jpg", "R").ReadData.ReturnBytes
    VBMAN.FileEx.CloseFile
    
    Set img = VBMAN.Image.Data(bytes)
    Debug.Print "MIME: " & img.ReturnMimeType        ' image/jpeg
    Debug.Print "Base64 length: " & Len(img.ReturnBase64)
    Set Image1.Picture = img.ReturnPicture
    
    ' 2. Base64 → byte array + StdPicture
    Dim b64 As String
    b64 = img.ReturnBase64
    
    Set img = VBMAN.Image.Data(b64)
    Dim newBytes() As Byte
    newBytes = img.ReturnBytes
    Set Image2.Picture = img.ReturnPicture
    
    ' 3. StdPicture → Base64 + byte array
    Set img = VBMAN.Image.Data(Image2.Picture)
    Dim picB64 As String
    picB64 = img.SetMimeType("image/bmp").ReturnBase64
    Dim picBytes() As Byte
    picBytes = img.ReturnBytes
    
    Debug.Print "Conversion complete!"
End Sub

Example 5: Batch Avatar Display

Get avatar Base64 from database in batch and display to multiple controls:

vb
Private Sub LoadAllAvatars()
    ' Query all user avatars
    VBMAN.Db.Sql("SELECT id, avatar FROM users").Fetch
    
    Dim i As Long
    For i = 0 To VBMAN.Db.RowCount - 1
        VBMAN.Db.Row i
        
        ' Find corresponding Image control by user ID
        Dim ctrlName As String
        ctrlName = "imgAvatar" & VBMAN.Db.Field("id")
        
        ' Display avatar in one line
        VBMAN.Image.(VBMAN.Db.Field("avatar")).ShowTo Me.Controls(ctrlName)
    Next i
End Sub

Conversion Flow Diagram

                    ┌─────────────┐
                    │   Data()    │ ← Chained entry (default member)
                    └─────────────┘

          ┌───────────────┼───────────────┐
          │               │               │
    Byte() array      Base64 string    StdPicture
          │               │               │
          └───────────────┼───────────────┘

              ┌───────────┼───────────┐
              │           │           │
        ReturnBytes  ReturnBase64  ReturnPicture
              │           │           │
              │      ReturnDataUri   ShowTo(control)
              │           │           │
              └───────────┼───────────┘

                    ┌─────────────┐
                    │ ReturnMimeType │ ← MIME type detection
                    └─────────────┘

Notes

  1. StdPicture → Byte Array: Internally saves a temporary file via SavePicture then reads it, outputs in BMP format
  2. MIME Type Detection: Only effective for byte array input; Base64 and StdPicture input requires manual specification
  3. Data URI Format: ReturnBase64 returns pure Base64, ReturnDataUri returns complete format with data: prefix
  4. GDI+ Initialization: Class internally manages GDI+ lifecycle automatically, initializes on first use, releases on class destruction
  5. Thread Safety: VBMAN.Image is a globally shared instance; for multiple independent conversion tasks, create New cImage

Best Practices

  1. Prefer ShowTo for Display: More concise than Set Image1.Picture = ...ReturnPicture
  2. Shorthand: VBMAN.Image.(base64Str) is more intuitive than the full form
  3. API Scenario: Receive Base64 image → ShowTo display; send image → ReturnBase64 encode
  4. HTML Embedding: Use ReturnDataUri to generate directly embeddable format
  5. Format Confirmation: Use ReturnMimeType to get type when uploading images, send along with request
  6. Independent Instance: Create New cImage for multi-thread or batch conversion scenarios

VB6 and LOGO copyright of Microsoft Corporation