cImage - Image Data Conversion Class
Overview
cImage provides mutual conversion functionality between Byte() ↔ Base64 ↔ StdPicture 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:
ShowTomethod directly displays images to Image/PictureBox controls - Default Member:
Datamethod is the default member, supportingVBMAN.Image.(base64Str)shorthand
Usage Patterns
' 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).ReturnPictureMethod Overview
Chained Entry Method
| Method | Description | Return |
|---|---|---|
| Data | Set data source (default member) | cImage (Me) |
Chained Helper Methods
| Method | Description | Return |
|---|---|---|
| SetMimeType | Manually set MIME type | cImage (Me) |
| ShowTo | Display image to target control | cImage (Me) |
Output Methods (Terminal Methods)
| Method | Description | Return |
|---|---|---|
| ReturnBytes | Output as byte array | Byte() |
| ReturnBase64 | Output as Base64 string | String |
| ReturnPicture | Output as StdPicture object | StdPicture |
| ReturnDataUri | Output as Data URI string | String |
| ReturnMimeType | Return detected MIME type | String |
Check Method
| Method | Description | Return |
|---|---|---|
| IsValid | Check if data is valid | Boolean |
Method Details
Data
Chained call entry point, accepts three data types. Default member, supports shorthand VBMAN.Image.(data).
Public Function Data(ByVal vData As Variant) As cImageParameters:
| Parameter | Type | Description |
|---|---|---|
vData | Variant | Data source, supports Byte() array, Base64 string, StdPicture object |
Supported Input Types:
| Type | Detection Basis | Example |
|---|---|---|
| Byte() array | VarType = vbArray Or vbByte | Byte data from reading an image file |
| Base64 string | VarType = vbString | Avatar Base64 returned by API |
| Data URI string | Starts with data: | data:image/png;base64,... |
| StdPicture object | IsObject(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:
' 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...").ReturnPictureSetMimeType
Manually set MIME type to override auto-detection results or supplement undetectable formats.
Public Function SetMimeType(ByVal MimeType As String) As cImageParameters:
| Parameter | Type | Description |
|---|---|---|
MimeType | String | MIME type, e.g., "image/jpeg", "image/png" |
Return: cImage (Me), supports chained calls
Example:
' 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").ReturnDataUriShowTo
Directly display image to the target control, the most convenient display method.
Public Function ShowTo(ByVal Target As Object) As cImageParameters:
| Parameter | Type | Description |
|---|---|---|
Target | Object | Any control object with a Picture property (Image, PictureBox, etc.) |
Return: cImage (Me), supports chained calls
Example:
' 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 Image2ReturnBytes
Convert image data to byte array output.
Public Function ReturnBytes() As Byte()Return: Byte() byte array
Example:
' 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.
Public Function ReturnBase64() As StringReturn: String - Pure Base64 string (without data: prefix)
Example:
' 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).PostReturnPicture
Convert image data to StdPicture object output, can be directly assigned to control's Picture property.
Public Function ReturnPicture() As StdPictureReturn: StdPicture object
Example:
' 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...").ReturnPictureReturnDataUri
Convert image data to Data URI format string output, suitable for direct embedding in HTML/CSS.
Public Function ReturnDataUri(Optional ByVal MimeType As String) As StringParameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
MimeType | String | No | MIME 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:
' 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.
Public Function ReturnMimeType() As StringReturn: String - MIME type string
Supported Detection Formats:
| Format | Magic Number (Hex) | MIME Type |
|---|---|---|
| JPEG | FF D8 FF | image/jpeg |
| PNG | 89 50 4E 47 | image/png |
| GIF | 47 49 46 | image/gif |
| BMP | 42 4D | image/bmp |
| WebP | 52 49 46 46 ... 57 45 42 50 | image/webp |
| ICO | 00 00 01 00 | image/x-icon |
Example:
' 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 SelectIsValid
Check if the data source is valid (whether data has been set via the Data method).
Public Function IsValid() As BooleanReturn: Boolean - Returns True when data is valid
Example:
Dim img As New cImage
img.Data(base64Str)
If img.IsValid Then
Set Image1.Picture = img.ReturnPicture
Else
MsgBox "Image data is invalid!"
End IfComprehensive Examples
Example 1: API Avatar Display
Get user avatar Base64 from API and display directly to Image control:
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 SubExample 2: Image Upload to Server
Convert local image to Base64 and upload to API:
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 SubExample 3: Image Data URI Embedding in HTML
Convert image to Data URI and embed in WebBrowser page:
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 SubExample 4: Full Image Format Conversion Flow
Complete demonstration of conversion between the three formats:
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 SubExample 5: Batch Avatar Display
Get avatar Base64 from database in batch and display to multiple controls:
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 SubConversion Flow Diagram
┌─────────────┐
│ Data() │ ← Chained entry (default member)
└─────────────┘
│
┌───────────────┼───────────────┐
│ │ │
Byte() array Base64 string StdPicture
│ │ │
└───────────────┼───────────────┘
│
┌───────────┼───────────┐
│ │ │
ReturnBytes ReturnBase64 ReturnPicture
│ │ │
│ ReturnDataUri ShowTo(control)
│ │ │
└───────────┼───────────┘
│
┌─────────────┐
│ ReturnMimeType │ ← MIME type detection
└─────────────┘Notes
- StdPicture → Byte Array: Internally saves a temporary file via
SavePicturethen reads it, outputs in BMP format - MIME Type Detection: Only effective for byte array input; Base64 and StdPicture input requires manual specification
- Data URI Format:
ReturnBase64returns pure Base64,ReturnDataUrireturns complete format withdata:prefix - GDI+ Initialization: Class internally manages GDI+ lifecycle automatically, initializes on first use, releases on class destruction
- Thread Safety:
VBMAN.Imageis a globally shared instance; for multiple independent conversion tasks, createNew cImage
Best Practices
- Prefer ShowTo for Display: More concise than
Set Image1.Picture = ...ReturnPicture - Shorthand:
VBMAN.Image.(base64Str)is more intuitive than the full form - API Scenario: Receive Base64 image →
ShowTodisplay; send image →ReturnBase64encode - HTML Embedding: Use
ReturnDataUrito generate directly embeddable format - Format Confirmation: Use
ReturnMimeTypeto get type when uploading images, send along with request - Independent Instance: Create
New cImagefor multi-thread or batch conversion scenarios