Posted: 17th Mar 2025 21:34
Loads an image and converts to a base64 string, prefixed with the necessary data text.

+ Code Snippet

// Project: png2b64 
// Created: 2025-03-17

SetErrorMode(2)
SetWindowTitle( "png2b64" )
SetWindowSize( 1024, 768, 0 )
SetVirtualResolution( 1024, 768 )
SetSyncRate(0, 0 )
UseNewDefaultFonts( 1 )


mystring$ = encodeImage("58027632709067.png")


x = opentowrite("raw:D:/AGK/png2b64/media/B64.txt")
writeLine(x, mystring$)
closefile(x)

end



function encodeImage(imgPath as string)
	
	// Not ideal to rely on file extension to determine 
	// image type but should work in most honest cases
	i = findStringReverse(imgPath, ".")
	ext$ = lower(mid(imgPath, i+1, len(imgPath)-i))
	
	prefix$ = "data:image/"+ext$+";base64,"
	
	
	
	pos = 0
		
	m = createMemblockFromFile(imgPath)
	L = getMemblockSize(m)
	
	// Determine size of encoded string
	n = ceil(4*(L/3.0))
	n = n + 4 - mod(n, 4)
 
	// Where to store the encoded string
	e = createMemblock(n)
	
	
	for i = 0 to L-1 step 3
		b1 = getMemblockByte(m, i)
		b2 = 0
		b3 = 0
		
		if (i+1 <= L) then b2 = getMemblockByte(m, i+1)
        if (i+2 <= L) then b3 = getMemblockByte(m, i+2)
        
        b4 = b1 >> 2
        b5 = ((b1&&0x3)<<4) || (b2>>4)
        b6 = ((b2&&0xf)<<2) || (b3>>6)
        b7 = b3 && 0x3f
        
        setMemblockByte(e, pos, b64_encodeByte(b4)) : inc pos
        setMemblockByte(e, pos, b64_encodeByte(b5)) : inc pos
        
        if i+1 < L
			setMemblockByte(e, pos, b64_encodeByte(b6)) : inc pos
		else
			setMemblockByte(e, pos, 61) : inc pos
        endif
        
        if i+2 < L
			setMemblockByte(e, pos, b64_encodeByte(b7)) : inc pos
		else
			setMemblockByte(e, pos, 61) : inc pos
        endif
        
	next i
 
	// free memory and get newly encoded string
	deleteMemblock(m)
	s$ = getMemblockString(e, 0, n)
	deleteMemblock(e)
	
endfunction prefix$+s$
 
 
 
 
function b64_encodeByte(byte)
	if byte < 26 then exitfunction 65+byte
	if byte < 52 then exitfunction 97+(byte-26)
	if byte < 62 then exitfunction 48+(byte-52)
	if byte = 62 then exitfunction 43
endfunction 47