u229
Applications Home|Email

 A Byte Array Class

Working with byte arrays is not easy when using vbscript and classic ASP. Perhaps you want to edit image files, pdf's or video files. How do you handle the different binary chunks while manipulating them, and how do you store them before putting the chunks together again? Here's a vbscript class that makes this task a little easier. It converts the binary data to hex strings which are appended to a text file. Then this file is loaded and the hex strings are converted back into a byte array using the ADO Stream Object.

This code is based on an article by Michael B. Smith.
http://blogs.brnets.com/michael/archive/2005/03/09/387.aspx

How to use the class:

First include the class.

<!--#include file="cByteArray.asp"-->

To call the cByteArray class:

Dim sFilePath, oByte, ByteArray, lngBytes

'// Load a binary file, in this case an image.
sFilePath = Server.MapPath("SomeBinaryFile.gif")

Set oByte = New cByteArray

With oByte
    '// Add some binary data as a byte array
    Call .AddBytes(LoadBytes(sFilePath))
    '// You may add as many binary chunks as you like.
    '// If you are using the MidB function the binary data is transferred as a string variable.
    '// This works just as well and gives us a handy tool to edit binary files.
    Call .AddBytes(MidB(LoadBytes(sFilePath), 50, 100))
    '// Read the number of bytes transferred to the class.
    lngBytes = .BytesTotal
    '// Return the bytes as a byte array. For example you may now save this
    '// to a binary file using the ADO Stream object.
    ByteArray = .ReturnBytes
End With

Set oByte = Nothing

And the LoadBytes routine looks like this. We are using the ADO Stream Object to load a binary file into a byte array:

Function LoadBytes(sFile)
    On Error Resume Next

    Dim oStream

    If IsEmpty(oStream) Then Set oStream = Server.CreateObject("ADODB.Stream")

    With oStream
        If .State = adStateOpen Then .State = adStateClosed
        .Type = adTypeBinary
        .Open
        .LoadFromFile sFile
        LoadBytes = .Read
    End With

    oStream.Close
    Set oStream = Nothing

End Function

Just to complete, here's a routine you may use to save the returned byte array to a file:

Sub SaveBytesToBinaryFile(ByteArray, sSavePath)
    On Error Resume Next

    Dim oStream

    If LenB(ByteArray) = 0 Then Exit Sub

    If IsEmpty(oStream) Then Set oStream = Server.CreateObject("ADODB.Stream")

    With oStream
        If .State = adStateOpen Then .State = adStateClosed
        .Type = adTypeBinary
        Call .Open
        Call .Write(ByteArray)
        Call .SaveToFile(sSavePath, adSaveCreateOverWrite)
        Call .Close
    End With

    Set oStream = Nothing

End Sub

View cByteArray.txt

Download demo project

Therefore: For that or this for it.
© www.u229.no