B4A Library MFLib - common functions, image manipulation, math parser

It's time to give something back to the community.​

My primary programming destination is Windows (Delphi and .NET). For my daily work, i created a function library long time ago which i use in almost all of my programs.
Now i convert parts of this library to Java for using it in B4A.

Here is my MFLib V1.07 for B4A and B4J.

Starting with V1.03 the library is separated in two versions: one for B4A (MFLib.jar) and one for B4J (jMFLib.jar). MFLib.jar contains additional functions for Android only.
In V1.04 an additionally library file was added (MFParser.jar/jMFParser.jar) with math parser functions.
In V1.06 the image functions are separated in its own library (MFImage.jar).

The new MaskedBitmap functions can be used to save app space. Two jpg files (bmp and mask) wants far less space than a png with alpha channel.

Function list of current version (more functions will be added in future).
For detailed description check the included example or inspect the xml with B4A Object Browser.

Base functions (MFLib.jar):

MF_Base.Version As String
Returns the MFLib version.

MF_Base.Copyright As String
Returns the MFLib copyright string.

{B4A only}
MF_Base.GetDeviceID As String
Returns a device id as string, based on a random UUID.
On first run, the id will be created and stored as file __id in "File.DirInternal".
Caution: The id changes on uninstalling/reinstalling app.

Date functions (MFLib.jar):

MF_Date.Easter(year As Integer) As Long
Calculates the date of easter sunday for the given year.

MF_Date.EncodeDate(year As Integer, month As Integer, day As Integer) As Long
Encodes year, month and day to standard date format. *

MF_Date.EncodeTime(hour As Integer, minute As Integer, second As Integer, milliSecond As Integer) As Long
Encodes hour, minute, second and millisecond to standard date format. *

MF_Date.EncodeDateTime(year As Integer, month As Integer, day As Integer, hour As Integer, minute As Integer, second As Integer, milliSecond As Integer) As Long
Encodes year, month, day, hour, minute, second and millisecond to standard date format. *

MF_Date.FromJulian(j As Double) As Long
Convert the given julian date to standard date format. *

MF_Date.IsLeapYear(year As Integer) As Boolean
Check if the given year is a leap year.

MF_Date.ToJulian(dt As Long) As Double
Convert the given standard date format * to julian date.

* standard date format: milliseconds since 1.1.1970

File functions (MFLib.jar):

MF_File.ApplicationPath As String
Returns the application file path (including application file name).
Does not work on Android.
CAUTION: this function works only in release mode. In debug mode, the path of MFLib.jar library will be returned.

MF_File.ChangeExt(path As String, newExt As String) As String
Change the file extension from a given path.

MF_File.CurrentDir As String
Returns the current directory.

MF_File.Exists(dirName As String, fileName As String, ignoreCase As Boolean, extendedCompare As Boolean) As Boolean
Check if file exists in directory, the filename can use wildcard characters (*, ?).

MF_File.FileDir(path As String) As String
Returns the full directory name from a given path.

MF_File.FileExt(path As String) As String
Returns the file extension from a given path.

MF_File.FileName(path As String) As String
Returns the file name from a given path.

MF_File.FileSeparator As String
Returns the file separator ("/" on Unix, "\" on Windows).

MF_File.Find(dirName As String, fileName As String, ignoreCase As Boolean, extendedCompare As Boolean) As String
Returns the real file name if the file exists in directory or an empty string if not.

MF_File.ListFiles(dirName As String, fileName As String, ignoreCase As Boolean, extendedCompare As Boolean) As List<String>
Returns a list of matching files from directory, the filename can use wildcard characters (*, ?).

MF_File.ListFiles2(dirName As String, fileName As String, ignoreCase As Boolean, extendedCompare As Boolean, recursive As Boolean, includeFiles As Boolean, includeDirs As Boolean) As List<String>
Returns a list of matching files from directory, the filename can use wildcard characters (*, ?).

MF_File.MakePath(dirName As String, fileName As String) As String
Combines directory name and file name with correct separator.

{B4J only}
MF_File.Move(dirSource As String, fileSource As String, dirTarget As String, fileTarget As String, replaceExisting As Boolean) As Boolean
Move a file or directory.
Source path and target path can belong to different drive.
To overwrite an existing target, replaceExisting must be True.

MF_File.PathSeparator As String
Returns the path separator (":" on Unix, ";" on Windows).

MF_File.Rename(dirSource As String, fileSource As String, dirTarget As String, fileTarget As String) As Boolean
Rename a file.

MF_File.TempDir As String
Returns the temp directory.

MF_File.UserDir As String
Returns the user home directory.​

Image functions (MFImage.jar): {B4A only}

MF_Image.ARGBget(pixel As Int) As Int()
Get the ARGB values from the given pixel as int array with 4 elements.

MF_Image.ARGBset(argb As Int()) As Int
Create a ARGB value from the given int array.

MF_Image.ARGBset2(a As Int, r As Int, g As Int, b As Int) As Int
Create a ARGB value from the given a, r, g, b values.

MF_Image.CreateMaskedBitmap(bmp As Bitmap, mask As Bitmap) As Bitmap
Creates a bitmap with alpha channel. The bitmap data comes from "bmp", the alpha data from "mask" (red channel). Both images must be 24 bit bitmaps with identical width and height.

MF_Image.EffectGrayscale(bmp As Bitmap) As Bitmap
Converts the given bitmap to grayscale.

MF_Image.EffectInvert(bmp As Bitmap) As Bitmap
Inverts the given bitmap.

MF_Image.EffectPosterize(bmp As Bitmap, offset As Int) As Bitmap
Assign posterize effect to given bitmap.

MF_Image.EffectSepia(bmp As Bitmap, depth As Int) As Bitmap
Converts the given bitmap to sepia toning. "depth" (1 - 255) defines the toning depth.

MF_Image.EffectSwapRG(bmp As Bitmap) As Bitmap
Swap green and blue color channel of the given bitmap.

MF_Image.EffectSwapRB(bmp As Bitmap) As Bitmap
Swap red and blue color channel of the given bitmap.

MF_Image.EffectSwapGB(bmp As Bitmap) As Bitmap
Swap red and green color channel of the given bitmap.

MF_Image.FilterBlur(bmp As Bitmap) As Bitmap
Use blur filter on bitmap.

MFImage.FilterConvolution3x3(bmp As Bitmap, matrix() As Int, factor As Int, offset As Int) As Bitmap
Use convolution filter on bitmap.

MF_Image.FilterEdge(bmp As Bitmap, soft As Boolean) As Bitmap
Use edge filter on bitmap.

MF_Image.FilterEmboss(bmp As Bitmap) As Bitmap
Use emboss filter on bitmap.

MF_Image.FilterEngrave(bmp As Bitmap, color As Boolean) As Bitmap
Use engrave filter on bitmap.

MF_Image.FilterSharpen(bmp As Bitmap) As Bitmap
Use sharpen filter on bitmap.

MF_Image.FilterSmooth(bmp As Bitmap) As Bitmap
Use smooth filter on bitmap.

MF_Image.FilterSobel(bmp As Bitmap) As Bitmap
Use sobel filter on bitmap.

MF_Image.BitmapToString(bmp As Bitmap, quality As Int) As String
Converts a bitmap to base64 encoded string.
If "quality" (possible value: 1 - 100) is 100, the bitmap will be compressed to png otherwise to jpg.

MF_Image.BitmapToString2(dir As String, fileName As String) As String
Converts a image file (jpg or png) to base64 encoded string.
The file will be converted in its own format without recompression.

MF_Image.BitmapToString3(dir As String, fileName As String, quality As Int) As String
Converts a image file (jpg or png) to base64 encoded string.
If "quality" (possible value: 1 - 100) is 100, the bitmap will be compressed to png otherwise to jpg.

MF_Image.StringToBitmap(str As String) As Bitmap
Converts a base64 encoded string (jpg or png) to bitmap.

MF_Image.StringToBitmap2(str As String, dir As String, fileName As String) As Boolean
Converts a base64 encoded string (jpg or png) to image file.
The file will be created in the corresponding image format, without recompression. The correct file extension (.jpg, .png) is automatically set.

MF_Image.StringToBitmap3(str As String, dir As String, fileName As String, quality As Int) As Boolean
Converts a base64 encoded string (jpg or png) to image file.
The compression type will be determined from the file extension, only ".jpg" and ".png" are allowed.

MF_Image.LoadMaskedBitmap(dir As String, fileName As String) As Bitmap
Loads a masked image from file. The mask file must have the same filename as the bitmap file with additional "_mask". If the bitmap filename is "image.jpg" then the mask file must be "image_mask.jpg". If no file extension is given then ".jpg" will be automatically added.

MF_Image.LoadMaskedBitmap2(dir As String, fileName As String, maskFileName As String) As Bitmap
Loads a masked image from file. If no file extension is given then ".jpg" will be automatically added.

MF_Image.SaveBitmap(bmp As Bitmap, dir As String, fileName As String, quality As Integer) As Boolean
Saves the given bitmap to file. The file type will be determined from the file extension, only ".jpg" and ".png" are allowed.
Info functions (MFLib.jar):

MF_Info.JavaVersion As String
Returns the java version.

MF_Info.Language As String
Returns the two-letter language code of the default locale.

MF_Info.Region As String
Returns the two-letter country code of the default locale.

MF_Info.SystemArchitecture As String
Returns the system architecture.

MF_Info.SystemName As String
Returns the name of the operating system.

MF_Info.SystemVersion As String
Returns the operating system version.

MF_Info.Timezone As String
Returns the default time zone.

MF_Info.UserName As String
Returns the user name.​

Math functions (MFLib.jar):

MF_Math.CompareFloat(value1 As Double, value2 As Double, tolerance As Double, percent As Boolean) As Integer
Compare two float numbers with tolerance.

MF_Math.CompareInt(value1 As Integer, value2 As Integer, tolerance As Integer, percent As Boolean) As Integer
Compare two int numbers with tolerance.

MF_Math.ConstrainFloat(value As Double, valueMin As Double, valueMax As Double) As Double
Check the min and max value of a float number and correct if needed.

MF_Math.ConstrainInt(value As Integer, valueMin As Integer, valueMax As Integer) As Integer
Check the min and max value of a int number and correct if needed.

MF_Math.EqualsFloat(value1 As Double, value2 As Double, tolerance As Double, percent As Boolean) As Boolean
Check if two float numbers are equal with tolerance.

MF_Math.EqualsInt(value1 As Integer, value2 As Integer, tolerance As Integer, percent As Boolean) As Boolean
Check if two int numbers are equal with tolerance.

MF_Math.MapFloat(value As Double, inMin As Double, inMax As Double, outMin As Double, outMax As Double) As Double
Map a float number from first min/max range to second min/max range.

MF_Math.MapInt(value As Integer, inMin As Integer, inMax As Integer, outMin As Integer, outMax As Integer) As Integer
Map a int number from first min/max range to second min/max range.

MF_Math.RoundTo(value As Double, digits As Integer) As Double
Rounds a number.​

String functions (MFLib.jar):

MF_String.Append(str As String, appendStr As String, delimiter As String) As String
Append string on another string with delimiter. If the first string is empty, no delimiter is used.

MF_String.Compare(str As String, pattern As String, ignoreCase As Boolean, extendedCompare As Boolean) As Boolean
Compares string with pattern, the pattern can use wildcard characters (*, ?).

MF_String.ContainsNumber(str As String) As Boolean
Check if a string contains numeric digit.

MF_String.BestLevenshtein(word As String, wordList As List<String>, threshold As Double, ignoreCase As Boolean) As List<String>
Compare the levenshtein distance between a word and all entries in a wordlist.
All entries with a score >= threshold (between 0.0 and 1.0) are part of the result list.

MF_String.Key(str As String) As String
Get the key from a string with format "key=value".

MF_String.Key2(str As String, delimiter As String) As String
Get the key from a string with format "key delimiter value".

MF_String.Left(str As String, num As Integer) As String
Get the left num chars of the given string.

MF_String.LevenshteinDistance(src As String, dest As String, ignoreCase As Boolean) As Int32
Calculate the levenshtein distance between two strings.

MF_String.Mid(str As String, pos As Int, num As Int) As String
Get num chars from the given string starting at pos.

MF_String.Right(str As String, num As Integer) As String
Get the right num chars of the given string.

MF_String.Reverse(str As String) As String
Reverse the given string.

MF_String.SetLength(str As String, len As Integer, rightAdjust As Boolean, fill As Char) As String
Set the length of the given string. The empty space is filled with the fill char.
If rightAdjust is True, the source string is right adjusted in the target string.

MF_String.SizeToStr(size As Int64, round As Boolean) As String
Converts the given number to string and formats it as size value (KB, MB, GB, ...).

MF_String.StringOfChar(ch As Char, len As Integer) As String
Returns a string of length len, filled with given char.

MF_String.TokenList(str As String, delim As String, repeater As Boolean, ignoreFirst As Boolean, ignoreLast As Boolean) As List<String>
Split a string at given delimiters.

MF_String.TokenList2(str As String, delim As String, startQuotas As String, endQuotas As String, repeater As Boolean, ignoreFirst As Boolean, ignoreLast As Boolean, includeQuotas As Boolean) As List<String>
Split a string at given delimiters.

MF_String.TokenListList(lst As List, delim As String, repeater As Boolean, ignoreFirst As Boolean, ignoreLast As Boolean) As List
Split a list of strings at given delimiters.
If repeater is true then following delimiters will inspected as one delimiter.
If ignoreFirst is True then a empty string before the first delimiter will be ignored.
If ignoreLast is True then a empty string after the last delimiter will be ignored.

MF_String.TokenListList2(lst As List, delim As String, startQuotas As String, endQuotas As String, repeater As Boolean, ignoreFirst As Boolean, ignoreLast As Boolean, includeQuotas As Boolean) As List
Split a list of strings at given delimiters.
If startQuotas and endQuotas are not empty, delimiters between quotas will be ignored.
If repeater is true then following delimiters will inspected as one delimiter.
If ignoreFirst is True then a empty string before the first delimiter will be ignored.
If ignoreLast is True then a empty string after the last delimiter will be ignored.
If includeQuotas is true then available quotas will included in the result.

MF_String.Translate(str As String, translateOut As String, translateIn As String, fill As Char, ignoreCase As Boolean) As String
Translate or erase characters in string. Reimplementation of the 'translate' function from REXX.
The string will be searched for the characters in 'translateIn' and replaced with the characters in 'translateOut'.
If 'translateOut' is shorter as 'translateIn' or a empty string, the found characters are replaced with the 'fill' char.
If the 'fill' char is Zero, the characters will be deleted.
If 'translageIn' is a empty string, the string will be filled with 'fill' char or set to uppercase if 'fill' is zero.

MF_String.Value(str As String) As String
Get the value from a string with format "key=value".

MF_String.Value2(str As String, delimiter As String) As String
Get the value from a string with format "key delimiter value".
Math parser functions (MFParser.jar):

MF_MathParser.Parse(formula As String) As Double
Parses the given formula and returns the result.
Multiple formulas can be used, separated with ";".
If a formula begins with "variable=", this variable will be set with the result.
Additionally a variable "result" with the result value of the last formula will be set.

MF_MathParser.CreateUserFunction(funcName As String, paramCount As Int, eventName As String) As Boolean
Create user defined function.

MF_MathParser.VariableClear, MF_MathParser.VariableExist(name As String) As Boolean, MF_MathParser.VariableGet(name As String) As Double, MF_MathParser.VariableRemove(name As String), MF_MathParser.VariableSet(name As String, value As Double)
 

Attachments

  • MFLib_v1.07.zip
    99.4 KB · Views: 1,047
Last edited:

Myr0n

Active Member
Licensed User
Longtime User
Thank you so much for this
 

MaFu

Well-Known Member
Licensed User
Longtime User
New version 1.05, see first post for download.

Enhancements in the parser lib.
The parser knows the following functions:
deg, rad, abs, acos, asin, atan, atan2, cbrt, ceil, constrain, cos, cosh, exp, floor, hypot, log, log10, map, max, min, pow, round, sin, sinh, sqrt, tan, tanh​
Variables can be set in formula and formulas can be combined:
x=2*2;y=sqrt(4);25/x+y​
User defined functions can be created, this functions raises an event on call (see example).
 
Last edited:

MaFu

Well-Known Member
Licensed User
Longtime User
New version 1.06, see first post for download.

The image functions are separated in its own library (MFImage.jar).

Image filters. The main filter is MFImage.FilterConvolution3x3(). It's optimized and about ten times faster as it's counterpart in RSImageProcessing library. The other available filters are all based on FilterConvolution3x3:
FilterBlur()
FilterEdge()
FilterEmboss()
FilterEngrave()
FilterSharpen()
FilterSmooth()
FilterSobel()​
 

MaFu

Well-Known Member
Licensed User
Longtime User
New version 1.07, see first post for download.

New functions in MFImage.jar.
Color split/combine:
ARGBget(), ARGBset(), ARGBset2()​
Image effects:
EffectGrayscale(), EffectInvert(), EffectPosterize(), EffectSepia(), EffectSwapRG(), EffectSwapRB(), EffectSwapGB()​
Image <-> BASE64 conversions:
BitmapToString(), BitmapToString2(), BitmapToString3(), StringToBitmap(), StringToBitmap2(), StringToBitmap3()
 

MaFu

Well-Known Member
Licensed User
Longtime User
MFLib Roadmap: additions coming in the next version(s)

MFImage functions partly rewrite as native functions (with NDK) for better performace (under progress).
RenderScript functions (under progress).
Astronomical functions (soon).
 

MaFu

Well-Known Member
Licensed User
Longtime User
Performance test of string compare function (with wildcards).
Compare between:
B4A Regex function (search pattern = ʺ^.*best.*$")
MFLib.Compare function (pure java and new NDK native version, search pattern = "*best*")
Short string (22 chars)
Regex: 0.0478 ms
MFLib.Compare (java): 0.0073 ms
MFLib.Compare (native): 0.0040 ms
Long string (162 chars)
Regex: 0.0510 ms
MFLib.Compare (java): 0.5028 ms
MFLib.Compare (native): 0.0161 ms​
 

slugger

Member
Licensed User
Longtime User
Hi,

thanks for the library.

I am trying the following:

B4X:
files = MF_File.ListFiles(File.DirAssets, "*.lng", True, False)

I have a few files with that extension but the returned list is empty.

If I copy the files to the DirDefaultExternal directory and run the same line of code changing File.DirAssets to File.DirDefaultExternal it works fine.
 

MaFu

Well-Known Member
Licensed User
Longtime User
I must admit that i haven't tested File.DirAssets. A scan of this folder should normally not needed because you know the files therein.
But i will have a look what goes wrong.
 

Bpick

Member
Licensed User
Longtime User
I am trying out the MFImage.BitmapToString3 function, as in
str=MFImage.BitmapToString3(MyPath, "0915140908.jpg", 100)

But str is showing a null value.

Must it be in the activity_create sub at all times?
 

MaFu

Well-Known Member
Licensed User
Longtime User
Are you sure, path and filename are correct?
BitmapToString3() returns an empty string if the bitmap cannot be loaded.
Another reason is out of memory if image is too big.
 

KZero

Active Member
Licensed User
Longtime User
This helped me so much ... thanks for sharing this gr8 stuff :)
 

ArminKH

Well-Known Member
Hi
Thanks 4 sharing this usefull lib
After many tests 4 converting an image 2 string by using encode to base 64 and then save my string to txt file i see my txt file size is smaller than my image size
Please explain 4 me this is Usual?or this is happen just 4 some images?the difference for a 500 kb image is about 300kb after converting it to a string by base 64 encoding
Thanks 4 your respons
 

ArminKH

Well-Known Member
Which function did you use?
BitmapToString()
BitmapToString2()
BitmapToString3()
If you use the first or last: which value did you set for "quality"?

I use First function and set quality to 100
But after encoding to string the txt file size is less than img size
 

MaFu

Well-Known Member
Licensed User
Longtime User
Your source image is JPG, right?
If you set the quality parameter for BitmapToString() to 100, the image will be encoded as PNG. A value < 100 use JPG format. Depending on the image content PNG can be much smaller as a low compressed JPG (but mostly not).
 
Top