base64 <---> buffer object

Get help for the alpha version of AutoHotkey v2 here. Please state the v2 version you are working with in the title when making a new topic.
JoeSchmoe
Posts: 52
Joined: 08 Dec 2014, 08:58

base64 <---> buffer object

31 Oct 2020, 22:50

Hi, is there a way to convert a small buffer object to base64 so I can store it in my AHK source code easily?

I'm making a clipboard manager style program and would like to have many small clipboards available long term. I'd like to store them as text strings in my source code and then convert them to ClipboardAll buffers when I want to use them.

Currently I'm keeping each clipboard in a different file, like this example from the help file:

Code: Select all

; to write one of the clipboards to a file:
ClipData := ClipboardAll()
FileOpen("Company Logo.clip", "w").RawWrite(ClipData)
; to later load it back into the clipboard:
ClipData := FileRead("Company Logo.clip", "RAW")  ; In this case, FileRead returns a Buffer.
A_Clipboard := ClipboardAll(ClipData)  ; Convert the Buffer to a ClipboardAll and assign it.
If it were possible to write multiple ClipDatas to a single binary file, that would work great, too.
swagfag
Posts: 4092
Joined: 11 Jan 2017, 17:59

Re: base64 <---> buffer object

01 Nov 2020, 08:24

Code: Select all

#DllLoad Crypt32.dll

bufferToBase64(buf) {
	if !DllCall('Crypt32.dll\CryptBinaryToString', 'Ptr', buf, 'UInt', buf.Size, 'UInt', 1, 'Ptr', 0, 'UInt*', numChars := 0)
		throw 'cant compute the destination buffer size, error: ' A_LastError

	bufString := BufferAlloc(numChars * 2)

	if !DllCall('Crypt32.dll\CryptBinaryToString', 'Ptr', buf, 'UInt', buf.Size, 'UInt', 1, 'Ptr', bufString, 'UInt*', bufString.Size)
		throw 'cant convert source buffer to base64, error: ' A_LastError

	return StrGet(bufString)
}

base64ToBuffer(ByRef strBase64) {
	if !DllCall('Crypt32.dll\CryptStringToBinary', 'Str', strBase64, 'UInt', 0, 'UInt', 1, 'Ptr', 0, 'UInt*', numBytes := 0, 'UInt*', 0, 'UInt*', 0)
		throw 'cant compute the destination buffer size, error: ' A_LastError

	buf := BufferAlloc(numBytes)

	if !DllCall('Crypt32.dll\CryptStringToBinary', 'Str', strBase64, 'UInt', 0, 'UInt', 1, 'Ptr', buf, 'UInt*', buf.Size, 'UInt*', 0, 'UInt*', 0)
		throw 'cant convert base64 to buffer, error: ' A_LastError

	return buf
}

base64ToClipboardAll(ByRef strBase64) {
	buf := base64ToBuffer(strBase64)
	return ClipboardAll(buf, buf.Size)
}

A_Clipboard := 'helloworld'

ClipData := ClipboardAll()
CompanyLogoBase64 := bufferToBase64(ClipData)
A_Clipboard := ''

A_Clipboard := base64ToClipboardAll(CompanyLogoBase64)
MsgBox A_Clipboard
If it were possible to write multiple ClipDatas to a single binary file, that would work great, too.
it is possible. invent ur own serialization/deserialization scheme and write out/parse the bytes according to it. use loops and FileObject's methods

Return to “AutoHotkey v2 Help”

Who is online

Users browsing this forum: No registered users and 2 guests