Page 1 of 1
Compress a string
Posted: Sun Mar 31, 2024 8:06 am
by loulou2522
Hi all,
My problem
I want to compress a string and after saving this string on an sqlite database. After i want to decompress this string from sqlite each time i need the content. Is-it possible ?
Thanks
Re: Compress a string
Posted: Sun Mar 31, 2024 9:13 am
by STARGĂ…TE
Here is an example.
You need the
Packer library and the
Database library
You can pack (compress) the string and store it as a BLOB type in the database.
Code: Select all
Enumeration
#File
#Database
EndEnumeration
UseSQLiteDatabase()
UseLZMAPacker()
; Create Database
Define DatabaseFile.s = GetTemporaryDirectory() + "Database.sql"
If CreateFile(#File, DatabaseFile)
CloseFile(#File)
If OpenDatabase(#Database, DatabaseFile, "", "")
If DatabaseUpdate(#Database, "CREATE TABLE example (compressed_string BLOB, size INT)")
Debug "Database with table created."
Else
Debug DatabaseError()
End
EndIf
Else
Debug "Can't open database!"
End
EndIf
Else
Debug "Can't create file!"
EndIf
; Storing
Define MyString.s = "This is a long string that needs to be compressed. This is a long string that needs to be compressed. This is a long string that needs to be compressed."
Define *BufferIn = UTF8(MyString)
Define SizeIn.i = MemorySize(*BufferIn)
Define *BufferOut = AllocateMemory(MemorySize(*BufferIn))
Define SizeOut.i = CompressMemory(*BufferIn, SizeIn, *BufferOut, SizeOut, #PB_PackerPlugin_Lzma)
SetDatabaseBlob(#Database, 0, *BufferOut, SizeOut)
SetDatabaseLong(#Database, 1, SizeIn)
If DatabaseUpdate(#Database, "INSERT INTO example (compressed_string, size) VALUES (?, ?);")
Debug "Compress string inserted. ("+SizeIn+" to "+SizeOut+" bytes)"
Else
Debug DatabaseError()
End
EndIf
FreeMemory(*BufferIn)
FreeMemory(*BufferOut)
; Read out
If DatabaseQuery(#Database, "SELECT compressed_string, size FROM example")
While NextDatabaseRow(#Database)
*BufferIn = AllocateMemory(DatabaseColumnSize(#Database, 0))
SizeIn = MemorySize(*BufferIn)
GetDatabaseBlob(#Database, 0, *BufferIn, SizeIn)
*BufferOut = AllocateMemory(GetDatabaseLong(#Database, 1))
SizeOut = MemorySize(*BufferOut)
UncompressMemory(*BufferIn, SizeIn, *BufferOut, SizeOut, #PB_PackerPlugin_Lzma)
MyString = PeekS(*BufferOut, -1, #PB_UTF8)
Debug "String uncompressed. ("+SizeIn+" to "+SizeOut+" bytes)"
Debug MyString
FreeMemory(*BufferIn)
FreeMemory(*BufferOut)
Wend
FinishDatabaseQuery(#Database)
Else
Debug DatabaseError()
EndIf
CloseDatabase(#Database)