ProgAndy

MySQL UDFs (without ODBC)

175 posts in this topic

#161 ·  Posted (edited)

@TheDcoder I am using this function in my scripts everyday and there's no problem. Show your code.

Edited by maniootek

Share this post


Link to post
Share on other sites



@maniootek Sorry, I cannot show the code as its a project of one of my clients!

Anyway, I have already found out the problem, the AV was blocking calls to the DLL!

1 person likes this

AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites

Here we have another strange issue again... Have anyone of you guys experienced a black hole? I mean, not a physical black hole :P, but a internet blackhole

I have a situation where sometimes the selected records don't get received and I get an empty array:

ZxotTno.png

And sometimes the Query which I send to the MySQL server never reaches to it... Also, in both cases NO error was being reported.


AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites

Theres a bug in this UDF that needs to be fixed.  If your querying a field, and the field is blank, it gives you zero.  Well what if the field is actually zero?  Theres no way to tell if the field is actually blank, or actually zero.

 

$data = DllStructGetData(DllStructCreate("char[" & $length & "]", $fieldPtr), 1)

should be:

$data = DllStructGetData(DllStructCreate("char[" & $length & "]", $fieldPtr), 1)
            if @error then $data = ""

 

Share this post


Link to post
Share on other sites

#165 ·  Posted

I am trying to read LONGBLOB data from a remote MySQL db, and then display the retrieved image/pic in an autoIT GUI. Would you have any examples of how to do this?

Briefly, what the below does is insert an image on my c:\ drive to a remote MySQL server. Using MySQL Workbench, I can see the image is stored as a BLOB and that the image looks fine when I open up the BLOB with Workbench.

The next part is where I am having difficulties. I am able to run the select, but clearly, since the data is a BLOB, it does not view properly in the different methods that ProgAndy uses in his included test.au3 file since he is displaying it as a string array. I was wondering what I could do to have the image show up in a very simple autoIT gui?

 

#include <array.au3>
#include <mysql.au3>
dim $file="C:\Users\nickz\Downloads\complexe_Test_SuiviClientLePheonix\images\3281-3281.jpg"
dim $f_handle

_MySQL_InitLibrary()

$MysqlConn = _MySQL_Init()

$connected = _MySQL_Real_Connect($MysqlConn,"host","user","password","dbname")

 If $connected = 0 Then
  $errno = _MySQL_errno($MysqlConn)
  MsgBox(0,"Error:",$errno & @LF & _MySQL_error($MysqlConn))
  If $errno = $CR_UNKNOWN_HOST Then MsgBox(0,"Error:","$CR_UNKNOWN_HOST" & @LF & $CR_UNKNOWN_HOST)
 Endif

$f_handle=FileOpen($file,16)
if @error <> 0 Then
 MsgBox(0,"Error:","file open error " & @error & @CRLF)
EndIf

$contents=FileRead($f_handle,FileGetSize($file))

 if @error <> 0 Then
  MsgBox(0,"Error:","file read error " & @error & @CRLF)
 EndIf
$bmp=String($contents)

;$query="INSERT INTO complexe_Test_SuiviClientLePheonix.tblCLIENTEXTENTION(attachement) values(" & $bmp & ")"
$query="UPDATE `complexe_Test_SuiviClientLePheonix`.`tblCLIENTEXTENTION` SET `attachement`=" & $bmp & " WHERE `NoClient`='3281'"

_MySQL_Real_Query($MysqlConn, $query)
;MsgBox(0,"SQL",$query)

 if @error <> 0 Then
  MsgBox(0,"Error:","SQL statement failed error =" & @error & @CRLF)
 EndIf

;~  address is a blob filed in the database

$query="SELECT attachement from `complexe_Test_SuiviClientLePheonix`.`tblCLIENTEXTENTION` WHERE `NoClient`='3281'"
_MySQL_Real_Query($MysqlConn, $query)
$res = _MySQL_Store_Result($MysqlConn)
msgbox(0,"",$query)

$fields = _MySQL_Num_Fields($res)

$rows = _MySQL_Num_Rows($res)
MsgBox(0, "", $rows & "-" & $fields)
ConsoleWrite("DataType=" & VarGetType($res) & @LF)
ConsoleWrite("DataType=" & VarGetType($fields) & @LF)
ConsoleWrite("DataType=" & VarGetType($rows) & @LF)
; Zugriff 1
MsgBox(0, '', "Zugriff Methode 1- Handarbeit")
Dim $array[$rows][$fields]
For $k = 1 To $rows
    $mysqlrow = _MySQL_Fetch_Row($res,$fields)

    $lenthsStruct = _MySQL_Fetch_Lengths($res)

    For $i = 1 To $fields
        $length = DllStructGetData($lenthsStruct, 1, $i)
        $fieldPtr = DllStructGetData($mysqlrow, 1, $i)
        $data = DllStructGetData(DllStructCreate("char[" & $length & "]", $fieldPtr), 1)
        $array[$k - 1][$i - 1] = $data
    Next
Next
_ArrayDisplay($array)

; Zugriff 2
MsgBox(0, '', "Zugriff Methode 2 - Reihe für Reihe")
_MySQL_Data_Seek($res, 0) ; nur zum zum Zurücksetzen an den Anfang der Abfrage
Do
$row1 = _MySQL_Fetch_Row_StringArray($res)
If @error Then ExitLoop
_ArrayDisplay($row1)
Until @error

MsgBox(0, '', "Zugriff Methode 3 - alles in ein 2D Array")
$array = _MySQL_Fetch_Result_StringArray($res)
_ArrayDisplay($array)

; Feldinformationen
MsgBox(0, '', "Zugriff Feldinformationen")
Dim $arFields[$fields][3]
For $i = 0 To $fields - 1
    $field = _MySQL_Fetch_Field_Direct($res, $i)
    $arFields[$i][0] = _MySQL_Field_ReadValue($field, "name")
    $arFields[$i][1] = _MySQL_Field_ReadValue($field, "table")
    $arFields[$i][2] = _MySQL_Field_ReadValue($field, "db")
Next
_ArrayDisplay($arFields)

; Cleanup
_MySQL_Free_Result($res)

_MySQL_Close($MysqlConn)

_MySQL_EndLibrary()
msgbox(0,"","DONE")
exit(0)

 

Share this post


Link to post
Share on other sites

#166 ·  Posted

Bump?

Share this post


Link to post
Share on other sites

#167 ·  Posted

You'd certainly gain from playing with Greencan example:

His code uses SQLite as the DB engine but can obviously be transposed to any ODBC or non-ODBC API.

 


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

#168 ·  Posted

Hi and thanks for pointing me to that demo. Got it working for that demo in no time. The issue is that it does way more than I actually need and I have spent most of the day trying to convert it from using SQLite to MySQL UDF and I am struggling big time....I can't seem to figure out the portions of this demo that I should be extracting for use and I can't migrate it to MySQL either... :-(

One example is the use of the PRAGMA commands.

I will keep trying here....

Share this post


Link to post
Share on other sites

#169 ·  Posted

OK. so I am focusing on the _Execbin function. My biggest problem is that when I debug the BLOB to the console in my script compared to the demo, the data returned in mine is only 4 characters in length.

Func _ExecBin($iItem)
    Local $aRow, $iKey, $aResult, $StringRemainder, $sDescription, $hFile, $iMaxRows, $Primary_Key, $sFileextension, $sEndOfFileNameFlag, $aTIFFDimension

    If $bGui_ImageView Then FileDelete($sFileName) ; delete previous file in temp folder

    ; identify Column position of Primary Key
    For $i = 0 To UBound($aNames) - 1 ; every column
        If StringUpper($aNames[$i]) = $sPrimary Then
            $Primary_Key = _GUICtrlListView_GetItemText($hListView, $iItem, $i)
            ExitLoop
        EndIf
    Next

    $Primary_Key = $iItem
    $sPrimary = "NoClient"

    $sSQL = "SELECT Attachement FROM " & $dbname & "." & $sTable & " WHERE " & $sPrimary & "='" & $Primary_Key & "'"
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $sSQL = ' & $sSQL & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
    If $iDebug Then ConsoleWrite(@ScriptLineNumber & " " & $sSQL & @CR)
    $connected = _MySQL_Real_Connect($MysqlConn, $dbhost, $dbuser, $dbpassword, $dbname, $dbport)

    If $connected = 0 Then
        $errno = _MySQL_errno($MysqlConn)
        MsgBox(0, "Erreur:", $errno & @LF & _MySQL_error($MysqlConn))
        If $errno = $CR_UNKNOWN_HOST Then MsgBox(0, "Erreur:", "$CR_UNKNOWN_HOST" & @LF & $CR_UNKNOWN_HOST)
        Exit (0)
    EndIf
    ;;~  attachement is a blob filed in the database
    ;   $noClient = InputBox("Veuillez scanner la carte", "", "", " M10")
    ;   If @error Then _Cleanup()

    Local $mysql_bool = _MySQL_Real_Query($MysqlConn, $sSQL)
    If $mysql_bool = $MYSQL_SUCCESS Then
        ;MsgBox($MB_SYSTEMMODAL, '', "Query OK")
    Else
        $errno = _MySQL_errno($MysqlConn)
        MsgBox($MB_SYSTEMMODAL, "Erreur:", $errno & @LF & _MySQL_error($MysqlConn))
        Return
    EndIf

    ;Local $res2 = _MySQL_Use_Result($MysqlConn)
    ;ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $res2 = ' & $res2 & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
    Local $res = _MySQL_Store_Result($MysqlConn)
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $res = ' & $res & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
    Local $fields = _MySQL_Num_Fields($res)
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $fields = ' & $fields & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

    Local $rows = _MySQL_Num_Rows($res)
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $rows = ' & $rows & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

    Local $mysqlrow, $lenthsStruct, $length, $fieldPtr, $data
    Local $array[$rows][$fields]

    For $k = 1 To $rows
        $mysqlrow = _MySQL_Fetch_Row($res, $fields)
        ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $mysqlrow = ' & $mysqlrow & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

        $lenthsStruct = _MySQL_Fetch_Lengths($res)
        ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $lenthsStruct = ' & $lenthsStruct & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

        For $i = 1 To $fields
            $length = DllStructGetData($lenthsStruct, 1, $i)
            ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $length = ' & $length & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
            $fieldPtr = DllStructGetData($mysqlrow, 1, $i)
            ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $fieldPtr = ' & $fieldPtr & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
            $data = DllStructGetData(DllStructCreate("char[" & $length & "]", $fieldPtr), 1)
            ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $data = ' & $data & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
            $array[$k - 1][$i - 1] = $data
            ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $array = ' & $array[0][0] & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
        Next
    Next
    _ArrayDisplay($array)

    ;_SQLite_QuerySingleRow(-1, $sSQL, $aRow)
    If @error Then Return SetError(1, 0, @error)

    If $data <> "" Then ; NOT an empty BLOB
        ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $data = ' & $data & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

 

@@ Debug(326) : $data = ÿØÿà

in the demo its:

@@ Debug(1495) : $aRow[0] = 0x5F5F477265656E43616E2E706E6700FFD8FFE000104A46494600010100000100010000FFDB00840009060614121115141014151 (I have truncated it for the post)

I don't understand the dllstructgetdata command but I think this is where it is failing. I also think there has to be a simpler way to read the 1 record returned as BLOB to $data, but I cannot figure it out...

Share this post


Link to post
Share on other sites

#170 ·  Posted

I'll have to leave that to someone used to this UDF. I'm not even a MySQL user so I can't give you any good advice here.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

#171 ·  Posted

I managed to figure out what was going on. Essentially the dllstruct was of type char instead of byte. Secondly, in the example, there was always a file name within the header with a null character. Since I was not loading the data with the embedded file name with the null character as the blob header, nothing was working.

I am going to clean up the code a bit and post it later. I am super happy this worked...thanks for pointing me to greencans demo.

 

Share this post


Link to post
Share on other sites

#172 ·  Posted

So the biggest issue I had was understanding the DLLStruct commands. Turned out that I needed to change it from char to byte and as well to upload the files with a proper header that included the filename.

Retrieving and displaying the image can be done with the following (Kudos to GreenCan and others!). Essentially, _Execbin(PK) performs a query and returns the blob based on the clientID which is the Primary key on the table.

Func _DisplayImage($sFile, $sDescription)
    Local $window_open, $aGIFDimension, $iOriginalW, $iOriginalH, $aClientSize, $nScale, $iPosX, $iPosY, $sTip, $iGUIWidth, $iGUIHeigth
    $window_open = WinList("ScanCartes") ; check If window already exists
    If $window_open[0][0] = 0 Then
    Else
        ; window already exist so only change the content
        _GIF_DeleteGIF($hGIF) ; first delete the previous image
        GUICtrlDelete($hGIFLabel) ; and delete the image label
    EndIf

    $aGIFDimension = _GIF_GetDimension($sFile)
    $iOriginalW = $aGIFDimension[0]
    $iOriginalH = $aGIFDimension[1]
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $aGIFDimension = ' & $aGIFDimension[0] & "W x " & $aGIFDimension[1] & "H" & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

    $aClientSize = WinGetClientSize($hGui_ImageView)
    $aClientSize[0] = 220
    $aClientSize[1] = 225
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $aClientSize = ' & $aClientSize[0] & "W x " & $aClientSize[1] & "H" & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
    ; Resize image to fit gui (trancexx)
    $nScale = 1
    While 1
        If $aClientSize[0] - 50 < $aGIFDimension[0] Or $aClientSize[1] - 70 < $aGIFDimension[1] Then
            $nScale /= 1.01
            $aGIFDimension[1] = Round($aGIFDimension[1] * $nScale)
            $aGIFDimension[0] = Round($aGIFDimension[0] * $nScale)
            ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $nScale = ' & $nScale & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
        Else
            ExitLoop
        EndIf
    WEnd
    While 1
        If $aClientSize[0] - 50 > $aGIFDimension[0] Or $aClientSize[1] - 70 > $aGIFDimension[1] Then
            $nScale *= 1.01
            $aGIFDimension[1] = Round($aGIFDimension[1] * $nScale)
            $aGIFDimension[0] = Round($aGIFDimension[0] * $nScale)
            ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $nScale = ' & $nScale & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
        Else
            ExitLoop
        EndIf
    WEnd
    ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $aGIFDimension = ' & $aGIFDimension[0] & "W x " & $aGIFDimension[1] & "H" & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console

    $iPosX = (@DesktopWidth - $aGIFDimension[0]) / 2
    $iPosY = 220
    If $iPosY + $aGIFDimension[1] > $aClientSize[1] - 50 Then $iPosY -= $aGIFDimension[1] - $aClientSize[1] + 50 ; not to cover buttons
    $hGIF = _GUICtrlCreateGIF($sFile, "", $iPosX, $iPosY, $aGIFDimension[0], $aGIFDimension[1])
    GUICtrlSetResizing(-1, 768 + 128 + 8 + 32) ; $GUI_DOCKSIZE + $GUI_DOCKVCENTER + $GUI_DOCKHCENTER + $GUI_DOCKTOP
    $sTip = "Size: " & $iOriginalW & " x " & $iOriginalH
    If $nScale < 1 Then $sTip &= @LF & "Resized to fit to: " & $aGIFDimension[0] & " x " & $aGIFDimension[1]
    GUICtrlSetTip($hGIF, $sTip, StringRegExpReplace($sFile, ".*\\", ""), 1)
    $hGIFLabel = GUICtrlCreateLabel($sDescription, 70, $iPosY + $aGIFDimension[1] + 5, @DesktopWidth - 140, 20, 1) ; $SS_CENTER
    GUISetState()

    Return
EndFunc   ;==>_DisplayImage

Func _ExecBin($iItem)
    Local $aResult, $StringRemainder, $sDescription, $hFile, $iMaxRows, $Primary_Key, $sFileextension, $sEndOfFileNameFlag, $aTIFFDimension

    If $bGui_ImageView Then FileDelete($sFileName) ; delete previous file in temp folder

    $Primary_Key = $iItem
    $sPrimary = "NoClient"

    $sSQL = "SELECT Attachement FROM " & $dbname & "." & $sTableClients & " WHERE " & $sPrimary & "='" & $Primary_Key & "'"
    If $iDebug Then ConsoleWrite(@ScriptLineNumber & " " & $sSQL & @CR)
    $connected = _MySQL_Real_Connect($MysqlConn, $dbhost, $dbuser, $dbpassword, $dbname, $dbport)

    If $connected = 0 Then
        $errno = _MySQL_errno($MysqlConn)
        MsgBox(0, "Erreur:", $errno & @LF & _MySQL_error($MysqlConn))
        If $errno = $CR_UNKNOWN_HOST Then MsgBox(0, "Erreur:", "$CR_UNKNOWN_HOST" & @LF & $CR_UNKNOWN_HOST)
        Exit (0)
    EndIf
    ;;~  attachement is a blob filed in the database
    ;   $noClient = InputBox("Veuillez scanner la carte", "", "", " M10")
    ;   If @error Then _Cleanup()

    Local $mysql_bool = _MySQL_Real_Query($MysqlConn, $sSQL)
    If $mysql_bool = $MYSQL_SUCCESS Then
        ;MsgBox($MB_SYSTEMMODAL, '', "Query OK")
    Else
        $errno = _MySQL_errno($MysqlConn)
        MsgBox($MB_SYSTEMMODAL, "Erreur:", $errno & @LF & _MySQL_error($MysqlConn))
        Return
    EndIf

    Local $res = _MySQL_Store_Result($MysqlConn)
    Local $fields = _MySQL_Num_Fields($res)
    Local $rows = _MySQL_Num_Rows($res)

    Local $mysqlrow, $lenthsStruct, $length, $fieldPtr, $data

    If $rows > 0 Then
        For $k = 1 To $rows
            $mysqlrow = _MySQL_Fetch_Row($res, $fields)
            $lenthsStruct = _MySQL_Fetch_Lengths($res)
            For $i = 1 To $fields
                $length = DllStructGetData($lenthsStruct, 1, $i)
                $fieldPtr = DllStructGetData($mysqlrow, 1, $i)
                $data = DllStructGetData(DllStructCreate("byte[" & $length & "]", $fieldPtr), 1)
            Next
        Next
    EndIf
    If $data <> "" Then ; NOT an empty BLOB
        If $bBlobRaw Then
            ; $aRow[0] = $aRow[0]  ; raw BLOB
            If StringMid($data, 3, 8) == "89504E47" Then ; png file signature
                $sFileextension = "png"
                $sFileName = _TempFile(@TempDir, "~", "." & $sFileextension)
                $sFileName = StringRight($sFileName, StringLen($sFileName) - StringInStr($sFileName, "\", 0, -1)) ; split filename from path
            ElseIf StringMid($data, 3, 4) == "424D" Then ; bmp file signature 424D
                $sFileextension = "bmp"
                $sFileName = _TempFile(@TempDir, "~", "." & $sFileextension)
                $sFileName = StringRight($sFileName, StringLen($sFileName) - StringInStr($sFileName, "\", 0, -1)) ; split filename from path
            ElseIf StringMid($data, 15, 8) == "4A464946" Then ; jpg file signature 4A464946
                $sFileextension = "jpg"
                $sFileName = _TempFile(@TempDir, "~", "." & $sFileextension)
                $sFileName = StringRight($sFileName, StringLen($sFileName) - StringInStr($sFileName, "\", 0, -1)) ; split filename from path
            ElseIf StringMid($data, 3, 6) == "474946" Then ; gif file signature 474946
                $sFileextension = "gif"
                $sFileName = _TempFile(@TempDir, "~", "." & $sFileextension)
                $sFileName = StringRight($sFileName, StringLen($sFileName) - StringInStr($sFileName, "\", 0, -1)) ; split filename from path
            ElseIf StringMid($data, 3, 8) == "00000100" Then ; ico file signature 00000100
                $sFileextension = "ico"
                $sFileName = _TempFile(@TempDir, "~", "." & $sFileextension)
                $sFileName = StringRight($sFileName, StringLen($sFileName) - StringInStr($sFileName, "\", 0, -1)) ; split filename from path
            ElseIf StringMid($data, 3, 8) == "49492A00" Then ; tif file Intel byte order signature 49492A00
                $sFileextension = "tif"
                $sFileName = _TempFile(@TempDir, "~", "." & $sFileextension)
                $sFileName = StringRight($sFileName, StringLen($sFileName) - StringInStr($sFileName, "\", 0, -1)) ; split filename from path
            ElseIf StringMid($data, 3, 8) == "4D4D002A" Then ; tif file Motorola byte order signature 4D4D002A
                $sFileextension = "tif"
                $sFileName = _TempFile(@TempDir, "~", "." & $sFileextension)
                $sFileName = StringRight($sFileName, StringLen($sFileName) - StringInStr($sFileName, "\", 0, -1)) ; split filename from path
            Else
                ; unknown format
                MsgBox(48, "Cannot View", "Sorry, the object cannot be recognized as an image", 3) ; not an error
                Return 1
            EndIf
        Else
            ; split file name and BLOB object
            ;$sEndOfFileNameFlag = StringInStr($aRow[0], "00")
            $sEndOfFileNameFlag = StringInStr($data, "00")
            If Int($sEndOfFileNameFlag / 2) = $sEndOfFileNameFlag / 2 Then $sEndOfFileNameFlag += 1
            ;$sFileName = BinaryToString(StringLeft($aRow[0], $sEndOfFileNameFlag - 1))
            $sFileName = BinaryToString(StringLeft($data, $sEndOfFileNameFlag - 1))
            If @error Then Return SetError(2, 0, @error)
            ;$aRow[0] = "0x" & StringTrimLeft($aRow[0], $sEndOfFileNameFlag + 1)
            $data = "0x" & StringTrimLeft($data, $sEndOfFileNameFlag + 1)
            $sFileextension = StringTrimLeft($sFileName, StringInStr($sFileName, "."))
        EndIf
        $aResult = StringRegExp($data, "(.{4094}|.{1,4094)", 3)
        $StringRemainder = StringTrimLeft($data, Int(StringLen($data) / 4094) * 4094)

        ; Currently, I display the file name of raw objects starting with a tilde ~
;~      If $bBlobRaw Then
;~          $sDescription = ""
;~      Else
        $sDescription = $sFileName
;~      EndIf

        If StringInStr(".gif;.png;.jpg;.tif;.bmp;.jpeg;.ico;", $sFileextension) > 0 Then
            $sFileName = @TempDir & "\" & $sFileName
        Else
            ; create executable objects in export folder
            $sFileName = $sExportFolder & "\" & $sFileName
        EndIf

        ; create object
        $hFile = FileOpen($sFileName, 16 + 2)
        If @error Then Return SetError(3, 0, 0)
        $iMaxRows = UBound($aResult)
        If $iMaxRows = 0 Then ; BLOB contains less than 4094 bytes
            FileWrite($hFile, $StringRemainder)
        Else
            FileWrite($hFile, $aResult[0]) ; "0x" already exists for the first row
            For $ii = 1 To $iMaxRows - 1
                FileWrite($hFile, "0x" & $aResult[$ii])
            Next
            FileWrite($hFile, "0x" & $StringRemainder)
        EndIf
        FileClose($hFile)
        If StringInStr(".gif;.png;.jpg;.bmp;.jpeg;.ico;", $sFileextension) > 0 Then

            _DisplayImage($sFileName, $sName)
        ElseIf StringInStr(".tiff;.tif;", $sFileextension) > 0 Then
            ; convert the tiff files to bmp, so that multipage tiff display the first page in the viewer
            ; it might be preferable to execute the multipage tiff so that it is displayed properly but
            ; I have no method to differentiate multipage from single page tiff...
            $aTIFFDimension = _GIF_GetDimension($sFileName)
            _ImageResize($sFileName, StringLeft($sFileName, StringInStr($sFileName, ".", 0, -1) - 0) & "bmp", $aTIFFDimension[0], $aTIFFDimension[1])
            _DisplayImage(StringLeft($sFileName, StringInStr($sFileName, ".", 0, -1) - 0) & "bmp", $sDescription)
            FileDelete(StringLeft($sFileName, StringInStr($sFileName, ".", 0, -1) - 0) & "bmp") ; delete the temporary file
        Else
            If $bGui_ImageView Then
                FileDelete($sFileName) ; delete last image file in temp folder
                GUIDelete($hGui_ImageView)
                $bGui_ImageView = False
            EndIf
            ToolTip("Executing...", MouseGetPos(0) + 20, MouseGetPos(1) + 20)
            ShellExecute($sFileName, "", @ScriptDir)
            ; just don't know how to export (move to @scriptdir on request) these files yet, so I don't delete the objects
            ; and I cannot delete here unless I ShellExecuteWait of course
            ToolTip("")
        EndIf
    Else
        ;MsgBox(0, "NOBLOB", "No Image Found, show default image")
        ;If Not FileExists(@ScriptDir & "\Resources\_DefaultImage.jpg") Then _Create_resources()
        _DisplayImage(@ScriptDir & "\Resources\_DefaultImage.jpg", "Photo non trouvée")
    EndIf

    Return 1
EndFunc   ;==>_ExecBin

And to load the BLOB data into MySQL, it will store the BLOB data along with the proper filename in the header for retrieval into a LONGBLOB field called Attachement:

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Res_Comment=imgUploader to store images to a MySQL DB as BLOB
#AutoIt3Wrapper_Res_Description=imgUploader to store images to a MySQL DB as BLOB
#AutoIt3Wrapper_Res_Fileversion=1.0.0.6
#AutoIt3Wrapper_Res_Fileversion_AutoIncrement=y
;#AutoIt3Wrapper_AU3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6 -w 7
#AutoIt3Wrapper_AU3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 6 -w 7
#AutoIt3Wrapper_Run_Tidy=y
#Tidy_Parameters=/sort_funcs /reel
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#include <array.au3>
#include <mysql.au3>
#include <libMySQLdll.au3>
#include <File.au3>
#include <MsgBoxConstants.au3>

Opt('MustDeclareVars', 1)

Global $sExtFilter = "bmp|gif|jpeg|jpg|png|tif|tiff"
Global $hTimer, $fDiff, $MysqlConn
Global $connected, $errno, $dbhost, $dbuser, $dbpassword, $dbname, $dbport

$dbhost = InputBox("DB Host", "Please enter the dbhost name (i.e. www.xyz.com, localhost)")
If @error Then Exit (0)
$dbuser = InputBox("DB User", "Please enter the dbuser name (i.e. sa)")
If @error Then Exit (0)
$dbpassword = InputBox("DB User Password", "Please enter the password for: <" & $dbuser & ">", "", "*")
If @error Then Exit (0)
$dbname = InputBox("DB Name", "Please enter the db name (i.e. xyz_DBName)")
If @error Then Exit (0)
$dbport = InputBox("DB Port", "Please enter the db port for MySQL (typically 3306)", "3306")
If @error Then Exit (0)

_MySQL_InitLibrary()

$MysqlConn = _MySQL_Init()

$connected = _MySQL_Real_Connect($MysqlConn, $dbhost, $dbuser, $dbpassword, $dbname, $dbport)

If $connected = 0 Then
    $errno = _MySQL_errno($MysqlConn)
    MsgBox(0, "Error:", $errno & @LF & _MySQL_error($MysqlConn))
    If $errno = $CR_UNKNOWN_HOST Then MsgBox(0, "Error:", "$CR_UNKNOWN_HOST" & @LF & $CR_UNKNOWN_HOST)
    Exit (0)
EndIf

_Browse()

; Cleanup
_MySQL_Close($MysqlConn)

_MySQL_EndLibrary()
$fDiff = TimerDiff($hTimer) ; Find the difference in time from the previous call of TimerInit. The variable we stored the TimerInit handlem is passed as the "handle" to TimerDiff.
MsgBox($MB_SYSTEMMODAL, "DONE", "DONE. Total upload time = " & Round($fDiff / 1000, 0) & " seconds")
Exit (0)

Func _Browse()
    Local $FSF, $FL2A, $iCnt = 0
    $FSF = FileSelectFolder("Browse for folder containing pictures", "C:", "C:\LLN")
    If Not @error And FileExists($FSF) Then
        If StringRight($FSF, 1) <> "\" Then $FSF &= "\"
        $FL2A = _FileListToArray($FSF, "*", 1)
        ;ConsoleWrite($FSF)
        ;ConsoleWrite(_ArrayDisplay($FL2A, "List of Files"))
        If Not @error Then
            ;ConsoleWrite("NO ERROR after fl2a")
            $hTimer = TimerInit() ; Begin the timer and store the handle in a variable.
            ; Display a progress bar window.
            ProgressOn("Progress Meter", "Images uploading...", "0%")
            ; Update the progress value of the progress bar window every second.
            For $i = 1 To $FL2A[0]
                If StringRegExp($FL2A[$i], "(?i)\.(" & $sExtFilter & ")", 0) Then
                    ConsoleWrite("Uploading:" & $FSF & $FL2A[$i] & @CRLF)
                    _uploadImage($FSF & $FL2A[$i], $FL2A[$i])
                    ProgressSet((Round($i / $FL2A[0] * 100, 0)), (Round($i / $FL2A[0] * 100, 0)) & "%")
                    $iCnt += 1
                EndIf
            Next
        EndIf
    EndIf
    ; Set the "subtext" and "maintext" of the progress bar window.
    ProgressSet(100, "Done", "Complete")
    Sleep(5000)
    ; Close the progress window.
    ProgressOff()
    MsgBox($MB_SYSTEMMODAL, "", "Images Processed: " & $iCnt, 10)
EndFunc   ;==>_Browse

Func _uploadImage($file, $fname)

    Local $f_handle, $contents, $bmp, $query, $mysql_bool
    Local $iPosition = StringInStr($fname, "-")
    ;ConsoleWrite("iPosition=" & $iPosition & @CRLF)

    If $iPosition > 0 Then
        Local $noClient = StringMid($fname, 1, $iPosition - 1)
        ConsoleWrite("NoClient=" & $noClient & @CRLF)
        $f_handle = FileOpen($file, 16)
        If @error <> 0 Then
            MsgBox($MB_SYSTEMMODAL, "Error:", "file open error " & @error & @CRLF)
        EndIf

        $contents = FileRead($f_handle, FileGetSize($file))

        If @error <> 0 Then
            MsgBox($MB_SYSTEMMODAL, "Error:", "file read error " & @error & @CRLF)
        EndIf
        ;(Binary($sFileName & Chr(0) & BinaryToString($sBinaryString)))
        ;Filename plus null chr(0) so that the retrieval can be done
        $bmp = String(StringToBinary($fname & Chr(0)) & $contents)

        ;$query="INSERT INTO complexe_Test_SuiviClientLePheonix.tblCLIENTEXTENTION(attachement) values(" & $bmp & ")"
        $query = "UPDATE `" & $dbname & "`.`tblCLIENTEXTENTION` SET `attachement`=" & $bmp & " WHERE `NoClient`='" & $noClient & "'"
        ;ConsoleWrite("UPDATE `" & $dbname & "`.`tblCLIENTEXTENTION` SET `attachement`=" & "$bmp" & " WHERE `NoClient`='" & $noClient & "'" & @CRLF & @CRLF)
        ;MsgBox(0, "SQL", $query)

        $mysql_bool = _MySQL_Real_Query($MysqlConn, $query)
        If $mysql_bool = $MYSQL_SUCCESS Then
            ;MsgBox($MB_SYSTEMMODAL, '', "Query OK")
        Else
            $errno = _MySQL_errno($MysqlConn)
            MsgBox($MB_SYSTEMMODAL, "Error:", $errno & @LF & _MySQL_error($MysqlConn))
        EndIf
    EndIf
EndFunc   ;==>_uploadImage

 

Hope this helps others.

Share this post


Link to post
Share on other sites

#173 ·  Posted

Hello everyone !

Unless I'm mistaken, I can not find the function" _MySQL_Real_Query" in mysql.au3 of ProgAndy ...

Can you help me ?

Thank you.


======> Tomy ... just for fun ;) <======

Share this post


Link to post
Share on other sites

#174 ·  Posted

5 hours ago, Tomy46 said:

Hello everyone !

Unless I'm mistaken, I can not find the function" _MySQL_Real_Query" in mysql.au3 of ProgAndy ...

Can you help me ?

Thank you.

post a location you got it from

I checked in my MySQL.au3 file and _MySQL_Real_Query is located in 1555 line

real.JPG

1 person likes this

Share this post


Link to post
Share on other sites

#175 ·  Posted

OK that's right!
The function has changed name in UDF : "_Query" ...
Thanks for the information anyway ;)


======> Tomy ... just for fun ;) <======

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Similar Content

    • junkew
      By junkew
      Since W8.1 (actually IE 11 with W7 will work also) microsoft has a Javascript runtime that can be called from scripting languages
      As shown in this example from C++: https://iobservable.net/blog/2013/11/12/introduction-to-jsrt/
      By loading either JSCRIPT9.DLL or CHAKRA.DLL you can embed ECMA JavaScript in your application
      And implemented here in AutoHotKey https://autohotkey.com/boards/viewtopic.php?f=6&t=5739
      Triggered by other threads: 
      https://www.autoitscript.com/forum/topic/185883-accessing-autoit-variables/ https://iobservable.net/blog/2013/11/12/introduction-to-jsrt/ https://www.autoitscript.com/forum/topic/184824-chakracore-udf-executing-javascript-in-autoit/ http://eclipsesource.com/blogs/2016/04/06/getting-started-with-microsoft-chakracore/
        This code is almost working but unfortunately not with the expected output. Someone seeing what is wrong? 
      It runs completely after fixes of DanyFirex 
       
      ;~ https://iobservable.net/blog/2013/11/ ;~ Should work on all windows versions with IE11 #AutoIt3Wrapper_UseX64=N #Region enum JsErrorCode : unsigned int Enum $JsNoError = 0, _ $JsErrorCategoryUsage = 0x10000, _ $JsErrorInvalidArgument, _ $JsErrorNullArgument, _ $JsErrorNoCurrentContext, _ $JsErrorInExceptionState, _ $JsErrorNotImplemented, _ $JsErrorWrongThread, _ $JsErrorRuntimeInUse, _ $JsErrorBadSerializedScript, _ $JsErrorInDisabledState, _ $JsErrorCannotDisableExecution, _ $JsErrorHeapEnumInProgress, _ $JsErrorArgumentNotObject, _ $JsErrorInProfileCallback, _ $JsErrorInThreadServiceCallback, _ $JsErrorCannotSerializeDebugScript, _ $JsErrorAlreadyDebuggingContext, _ $JsErrorAlreadyProfilingContext, _ $JsErrorIdleNotEnabled, _ $JsErrorCategoryEngine = 0x20000, _ $JsErrorOutOfMemory, _ $JsErrorCategoryScript = 0x30000, _ $JsErrorScriptException, _ $JsErrorScriptCompile, _ $JsErrorScriptTerminated, _ $JsErrorScriptEvalDisabled, _ $JsErrorCategoryFatal = 0x40000, _ $JsErrorFatal ;~ }JsErrorCode; #EndRegion enum JsErrorCode : unsigned int #Region typedef enum JsRuntimeVersion Enum $JsRuntimeVersion10 = 0, $JsRuntimeVersion11 = 1 #EndRegion typedef enum JsRuntimeVersion ; Create callback function. Local $hPrintf = DllCallbackRegister("_printf", "long", "ptr;bool;ptr;ushort;ptr") Local $hJSRuntime = DllOpen("c:\windows\system32\jscript9.dll") $JsRuntimeAttributeNone = 0x00000000 ;~ #RequireAdmin Example() Func Example() Local $script = "native.printf('hello world')" ;~ Local $script = "native.printf('number=%#x string=%s\n', 255, 'test')" ;~ Local $script = "(()=>{return 'Hello world!';})()" ;~ Local $script = "var x='helloworld'; return x;" ;~ Local $script = "var x=10;" & @CRLF & "var y=11;" ;~ Local $script = "(42);" ;~ Local $script = "(" & @CRLF ;~ $script=$script & "host.echo(JSON.stringify({foo:'bar'}));)" & @CRLF ;~ $script=$script & "42 // The script's result :) "& @CRLF ;~ $script=$script & ")"& @CRLF ;~ $script=$script & "class Host {"& @CRLF ;~ $script=$script & " echo(s) {"& @CRLF ;~ $script=$script & " MsgBox %s%"& @CRLF ;~ $script=$script & " }"& @CRLF ;~ $script=$script & "}"& @CRLF Local $aResult Local $runtime Local $context ;~ // Create a runtime ;~ JsCreateRuntime(JsRuntimeAttributeNone, nullptr, &runtime); $runtime = _JsCreateRuntime($JsRuntimeAttributeNone, 0, $runtime) ; ;~ // Create an execution context. ;~ JsCreateContext(runtime, &context); $context = _JsCreateContext($runtime, $context) ;~ // Now set the current execution context. ;~ JsSetCurrentContext(context); _JsSetCurrentContext($context) ; ; Get the Global object for adding stuff ;~ JsGetGlobalObject(&global); Local $global $global = _JsGetGlobalObject($global) ;~ JsPropertyIdRef nativeProp; ;~ JsGetPropertyIdFromName(L"native", &nativeProp); Local $nativeProp $nativeProp = _JsGetPropertyIdFromName("native", $nativeProp) ;~ JsValueRef nativeObj; ;~ JsCreateObject(&nativeObj); Local $nativeObj $nativeObj = _JsCreateObject($nativeObj) ;~ JsPropertyIdRef printfProp; ;~ JsGetPropertyIdFromName(L"printf", &printfProp); Local $printfProp $printfProp = _JsGetPropertyIdFromName("printf", $printfProp) ;~ JsValueRef printfFunc; ;~ JsCreateFunction(PrintFormat, nullptr, &printfFunc); Local $printfFunc $printfFunc = _JsCreateFunction(DllCallbackGetPtr($hPrintf), 0, $printfFunc) ;~ JsSetProperty(nativeObj, printfProp, printfFunc, true); _JsSetProperty($nativeObj, $printfProp, $printfFunc, True) ;~ JsSetProperty(global, nativeProp, nativeObj, true); _JsSetProperty($global, $nativeProp, $nativeObj, True) ;~ STDAPI_(JsErrorCode) JsCreateFunction( ;~ _In_ JsNativeFunction nativeFunction, ;~ _In_opt_ void *callbackState, ;~ _Out_ JsValueRef *function ;~ ); ; Get a JsValueRef for our Host object ;~ hostRef := ToJsValue(Host) ;~ $aResult=DllCall($hJSRuntime, "int","JsVariantToValue", "ptr", &variant, "ptr*", valref) ; Pass our Host object to the script engine ;~ DllCall("jscript9\JsSetProperty", "ptr", globalObject, "ptr", hostPropertyId, "ptr", hostRef, "int", true) ;~ // Run the script. ;~ STDAPI_(JsErrorCode) JsRunScript( ;~ _In_z_ const wchar_t *script, ;~ _In_ JsSourceContext sourceContext, ;~ _In_z_ const wchar_t *sourceUrl, ;~ _Out_ JsValueRef *result ;~ ); Local $currentSourceContext = 1 ;~ JsRunScript(script.c_str(), currentSourceContext++, L"", &result); Local $result = "" Local $sourceURL = "" $aResult = DllCall($hJSRuntime, "int", "JsRunScript", "WSTR", $script, "UINT*", $currentSourceContext, "wstr", "dummysource.js", "WSTR*", $result) ConsoleWrite("Error 11: " & @error & @CRLF) If @error = 0 Then ConsoleWrite($aResult[0] & ";" & $aResult[1] & ";" & $aResult[2] & ";" & $aResult[3] & ";" & $aResult[4] & @CRLF) EndIf ;~ // Convert your script result to String in JavaScript redundant if your script returns a String ;~ JsValueRef resultJSString; ;~ STDAPI_(JsErrorCode) JsConvertValueToString( ;~ _In_ JsValueRef value, ;~ _Out_ JsValueRef *stringValue ;~ ); ;~ JsConvertValueToString(result, &resultJSString); ;~ $aResult=DllCall($hJSRuntime, "int", "JsConvertValueToString", "WSTR", $script, "long", 1, "WSTR*",0, "WSTR*", $result) ;~ consolewrite("Error 4: " & @error & @CRLF) ;~ if @error=0 Then ;~ consolewrite($aResult[0] & ";" & $aResult[1] & ";" & $aResult[2] & ";" & $aResult[3] & ";" & $aResult[4] & @CRLF) ;~ EndIf ;~ ;~ // Project script result back to C++. ;~ const wchar_t *resultWC; ;~ size_t stringLength; ;~ JsStringToPointer(resultJSString, &resultWC, &stringLength); ;~ wstring resultW(resultWC); ;~ cout << string(resultW.begin(), resultW.end()) << endl; ;~ system("pause"); ;~ // Dispose runtime ;~ JsSetCurrentContext(JS_INVALID_REFERENCE); ;~ JsDisposeRuntime(runtime); Return 0 ; EndFunc ;==>Example ; Create callback function. ;~ JsValueRef CALLBACK PrintFormat(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) ;~ { ;~ const wchar_t *format; ;~ size_t length; ;~ JsStringToPointer(arguments[1], &format, &length); ;~ VARIANT variant; ;~ JsValueToVariant(arguments[2], &variant); ;~ const wchar_t *str; ;~ JsStringToPointer(arguments[3], &str, &length); ;~ wprintf(format, variant.intVal, str); ;~ return JS_INVALID_REFERENCE; ;~ } ;~ typedef _Ret_maybenull_ JsValueRef (CALLBACK * JsNativeFunction)( ;~ _In_ JsValueRef callee, ;~ _In_ bool isConstructCall, ;~ _In_ JsValueRef *arguments, ;~ _In_ unsigned short argumentCount ;~ ); Func _printf($callee, $isConstructCall, $arguments, $argumentCount, $callbackState) ConsoleWrite("there we are with " & $argumentCount & " arguments" & @CRLF) Local $tArgs = DllStructCreate("ptr JsValues[" & $argumentCount & "]", $arguments) ;~ STDAPI_(JsErrorCode) JsConvertValueToString( ;~ _In_ JsValueRef value, ;~ _Out_ JsValueRef *stringValue ;~ ); ;~ JsConvertValueToString(result, &resultJSString); local $tresult $aResult=DllCall($hJSRuntime, "int", "JsConvertValueToString", "ptr", DllStructGetData($tArgs,1,2), "ptr*", $tresult) consolewrite("Error 4: " & @error & @CRLF) if @error=0 Then consolewrite( $aResult[0] & ";" & $aResult[1] & ";" & $aResult[2] & @CRLF) $tresult=$aresult[2] EndIf ;~ STDAPI_(JsErrorCode) JsValueToVariant( ;~ _In_ JsValueRef object, ;~ _Out_ VARIANT *variant ;~ ); ;~ Local $aResult = DllCall($hJSRuntime, "dword", "JsValueToVariant", "ptr", $arguments[0], "ptr*", 0) ;~ If @error Then Return SetError(3, 0, @error) ;~ If $aResult[0] <> 0 Then Return SetError(4, 0, $aResult[0]) ;~ consolewrite($aResult[2]) Local $aResult = DllCall($hJSRuntime, "dword", "JsStringToPointer", "ptr", $tResult, "ptr*", 0, "int*", 0) If @error Then Return SetError(3, 0, @error) If $aResult[0] <> 0 Then Return SetError(4, 0, $aResult[0]) Local $tString = DllStructCreate("wchar string["&$aResult[3]&"]", $aResult[2]) consolewrite("+Parameter: " & $tString.string & @CRLF) Return 0 EndFunc ;==>_printf ;~ typedef void *JsRuntimeHandle; ;~ // Create a runtime. ;~ Edge mode signature STDAPI_(JsErrorCode) JsCreateRuntime( ;~ _In_ JsRuntimeAttributes attributes, ;~ _In_opt_ JsThreadServiceCallback threadService, ;~ _Out_ JsRuntimeHandle *runtime); ;~ Legacy mode signature ;~ STDAPI_(JsErrorCode) JsCreateRuntime( ;~ _In_ JsRuntimeAttributes attributes, ;~ _In_ JsRuntimeVersion version, ;~ _In_opt_ JsThreadServiceCallback threadService, ;~ _Out_ JsRuntimeHandle *runtime ;~ ); ;~ $runtime=_JsCreateRuntime(JsRuntimeAttributeNone, 0, $runtime); Func _JsCreateRuntime($JsRuntimeAttributeNone, $JSRuntimeVersion, $runtime) $aResult = DllCall($hJSRuntime, "int", "JsCreateRuntime", "int", $JsRuntimeAttributeNone, "int", $JSRuntimeVersion, "ptr", 0, "ptr*", $runtime) If @error Then Return SetError(1, @error, 0) Return $aResult[4] EndFunc ;==>_JsCreateRuntime ;~ // Edge mode signature ;~ STDAPI_(JsErrorCode) JsCreateContext( ;~ _In_ JsRuntimeHandle runtime, ;~ _Out_ JsContextRef *newContext); ;~ // Legacy mode signature ;~ STDAPI_(JsErrorCode) JsCreateContext( ;~ _In_ JsRuntimeHandle runtime, ;~ _In_ IDebugApplication *debugApplication, ;~ _Out_ JsContextRef *newContext ;~ ); ;~ JsCreateContext(runtime, &context); Func _JsCreateContext($runtime, $context) $aResult = DllCall($hJSRuntime, "int", "JsCreateContext", "ptr", $runtime, "ptr", 0, "ptr*", $context) If @error Then Return SetError(1, @error, 0) Return $aResult[3] EndFunc ;==>_JsCreateContext ;~ STDAPI_(JsErrorCode) JsSetCurrentContext( ;~ _In_ JsContextRef context ;~ ); ;~ JsSetCurrentContext(context); Func _JsSetCurrentContext($context) $aResult = DllCall($hJSRuntime, "int", "JsSetCurrentContext", "ptr", $context) If @error Then Return SetError(1, @error, 0) Return $JsNoError EndFunc ;==>_JsSetCurrentContext ; Get the Global object for adding stuff ;~ STDAPI_(JsErrorCode) JsGetGlobalObject( ;~ _Out_ JsValueRef *globalObject ;~ ); ;~ JsValueRef global; ;~ JsGetGlobalObject(&global); Func _JsGetGlobalObject($global) $aResult = DllCall($hJSRuntime, "int", "JsGetGlobalObject", "ptr*", $global) If @error Then Return SetError(1, @error, 0) Return $aResult[1] EndFunc ;==>_JsGetGlobalObject ; Get a property ID for the name "host" ;~ STDAPI_(JsErrorCode) JsGetPropertyIdFromName( ;~ _In_z_ const wchar_t *name, ;~ _Out_ JsPropertyIdRef *propertyId ;~ ); ;~ DllCall("jscript9\JsGetPropertyIdFromName", "wstr", "host", "ptr*", hostPropertyId) ;~ local $hostPropertyID ;~ $aResult=DllCall($hJSRuntime, "int","JsGetPropertyIdFromName", "wstr", "host", "ptr*", $hostPropertyId) ;~ consolewrite("Error 5: " & @error & @CRLF) ;~ if @error=0 Then ;~ consolewrite($aResult[0] & ";" & $aResult[1] & ";" & $aResult[2] & @CRLF) ;~ EndIf ;~ JsPropertyIdRef nativeProp; ;~ JsGetPropertyIdFromName(L"native", &nativeProp); Func _JsGetPropertyIdFromName($propname, $nativeProp) $aResult = DllCall($hJSRuntime, "int", "JsGetPropertyIdFromName", "wstr", $propname, "ptr*", $nativeProp) If @error Then Return SetError(1, @error, 0) Return $aResult[2] EndFunc ;==>_JsGetPropertyIdFromName ;~ STDAPI_(JsErrorCode) JsCreateObject( ;~ _Out_ JsValueRef *object ;~ ); ;~ JsValueRef nativeObj; ;~ JsCreateObject(&nativeObj); Local $nativeObj Func _JsCreateObject($JSRTobject) $aResult = DllCall($hJSRuntime, "int", "JsCreateObject", "ptr*", $JSRTobject) If @error Then Return SetError(1, @error, 0) Return $aResult[1] EndFunc ;==>_JsCreateObject ;~ STDAPI_(JsErrorCode) JsCreateFunction( ;~ _In_ JsNativeFunction nativeFunction, ;~ _In_opt_ void *callbackState, ;~ _Out_ JsValueRef *function ;~ ); Func _JsCreateFunction($fncCallBackPtr, $callbackState, $fncVar) $aResult = DllCall($hJSRuntime, "int", "JsCreateFunction", "ptr", $fncCallBackPtr, "ptr*", $callbackState, "ptr*", $fncVar) If @error Then Return SetError(1, @error, 0) Return $aResult[3] EndFunc ;==>_JsCreateFunction ;~ JsSetProperty(nativeObj, printfProp, printfFunc, true); ;~ STDAPI_(JsErrorCode) JsSetProperty( ;~ _In_ JsValueRef object, ;~ _In_ JsPropertyIdRef propertyId, ;~ _In_ JsValueRef value, ;~ _In_ bool useStrictRules ;~ ); Func _JsSetProperty($Obj, $Prop, $Func, $val) ; $aResult = DllCall($hJSRuntime, "int", "JsSetProperty", "ptr", $Obj, "ptr", $Prop, "ptr", $Func, "int", $val) If @error Then Return SetError(1, @error, 0) EndFunc ;==>_JsSetProperty  
    • Fhelipe
      By Fhelipe
      Nothing More
    • ur
      By ur
      Is there anyway to create an assembly for AutoIT so that I can use that in Powershell or Dotnet supported languages like c#.
      Like I want to use the functionality of _ArrayDisplay of AutoIT in C# by creating a assmbly/library and using that in the target language.
    • UEZ
      By UEZ
      Since I disovered FreeBasic I decided to create a DLL to implement much faster image processing functionality to AutoIt.
      Following functions are implemented yet:
      _GDIPlus_BitmapApplyFilter_BWJJNDithering _GDIPlus_BitmapApplyFilter_Cartoon1 _GDIPlus_BitmapApplyFilter_ColorAccent _GDIPlus_BitmapApplyFilter_Convolution_AnotherBlur _GDIPlus_BitmapApplyFilter_Convolution_BoxBlur _GDIPlus_BitmapApplyFilter_Convolution_EdgeDetection1 _GDIPlus_BitmapApplyFilter_Convolution_EdgeDetection2 _GDIPlus_BitmapApplyFilter_Convolution_EdgeDetection3 _GDIPlus_BitmapApplyFilter_Convolution_EdgeDetection4 _GDIPlus_BitmapApplyFilter_Convolution_EdgeDetection5 _GDIPlus_BitmapApplyFilter_Convolution_EdgeDetection6 _GDIPlus_BitmapApplyFilter_Convolution_Emboss1 _GDIPlus_BitmapApplyFilter_Convolution_Emboss45Degree _GDIPlus_BitmapApplyFilter_Convolution_EmbossTopLeftBottomRight _GDIPlus_BitmapApplyFilter_Convolution_Gaussian3x3 _GDIPlus_BitmapApplyFilter_Convolution_Gaussian5x5_1 _GDIPlus_BitmapApplyFilter_Convolution_Gaussian5x5_2 _GDIPlus_BitmapApplyFilter_Convolution_GaussianBlur _GDIPlus_BitmapApplyFilter_Convolution_IntenseEmboss _GDIPlus_BitmapApplyFilter_Convolution_Kirsch _GDIPlus_BitmapApplyFilter_Convolution_Laplace1 _GDIPlus_BitmapApplyFilter_Convolution_Laplace2 _GDIPlus_BitmapApplyFilter_Convolution_Laplace3 _GDIPlus_BitmapApplyFilter_Convolution_LaplacianOfGaussian _GDIPlus_BitmapApplyFilter_Convolution_ManualMatrix _GDIPlus_BitmapApplyFilter_Convolution_MotionBlur _GDIPlus_BitmapApplyFilter_Convolution_Outline3x3 _GDIPlus_BitmapApplyFilter_Convolution_Prewitt _GDIPlus_BitmapApplyFilter_Convolution_Sharpen1 _GDIPlus_BitmapApplyFilter_Convolution_Sharpen2 _GDIPlus_BitmapApplyFilter_Convolution_Sobel _GDIPlus_BitmapApplyFilter_Convolution_SovelVsPrewitt _GDIPlus_BitmapApplyFilter_Convolution_TriangleBlur _GDIPlus_BitmapApplyFilter_Convolution_Unsharp _GDIPlus_BitmapApplyFilter_Convolution_Unsharp5x5 _GDIPlus_BitmapApplyFilter_Dilatation _GDIPlus_BitmapApplyFilter_DistortionBlur _GDIPlus_BitmapApplyFilter_Edges _GDIPlus_BitmapApplyFilter_Erosion _GDIPlus_BitmapApplyFilter_FishEye _GDIPlus_BitmapApplyFilter_Indexed _GDIPlus_BitmapApplyFilter_Jitter _GDIPlus_BitmapApplyFilter_Kuwahara _GDIPlus_BitmapApplyFilter_Linellism _GDIPlus_BitmapApplyFilter_Median _GDIPlus_BitmapApplyFilter_Median2 _GDIPlus_BitmapApplyFilter_OilPainting _GDIPlus_BitmapApplyFilter_PenSketch _GDIPlus_BitmapApplyFilter_PenSketch2 _GDIPlus_BitmapApplyFilter_Pixelate _GDIPlus_BitmapApplyFilter_Pointillism _GDIPlus_BitmapApplyFilter_RadialBlur _GDIPlus_BitmapApplyFilter_Raster _GDIPlus_BitmapApplyFilter_Swirl _GDIPlus_BitmapApplyFilter_SymmetricNearestNeighbour _GDIPlus_BitmapApplyFilter_TiltShift _GDIPlus_BitmapApplyFilter_TimeWarp _GDIPlus_BitmapApplyFilter_Wave _GDIPlus_BitmapApplyFilter_XRay  
      Since I am absolutely a newbie in FreeBasic, the DLL may contain errors.  Please report any bug.
       
      FreeBasic source code can be found here: https://pastebin.com/Lugp6rCR
       
      To do:
      add function headers with descriptions speed-up FB code -> partly done add more filters -> ongoing  
      Credits to:
      Jakub Szymanowski rdc Dewald Esterhuizen Santhosh G_  Christian Graus www.gutgames.com  
      Have fun.
       
      Download link: 
       
      You can compare the speed with AutoIt version:
      #AutoIt3Wrapper_Version=b #include <Array.au3> #include <GDIPlus.au3> Global $sFile = FileOpenDialog("Select an image", "", "Images (*.jpg;*.png;*.gif;*.bmp)") If @error Then Exit _GDIPlus_Startup() Global Const $STM_SETIMAGE = 0x0172 Global Const $hImage = _GDIPlus_ImageLoadFromFile($sFile) Global Const $iW = _GDIPlus_ImageGetWidth($hImage), $iH = _GDIPlus_ImageGetHeight($hImage) Global Const $hGUI = GUICreate("GDI+ Image Filters", $iW * 2, $iH) Global $fProg = 0, $iEnd = $iW * $iH - 1 AdlibRegister("Progress", 490) Global $t = TimerInit() Global Const $hGDIBitmap = _GDIPlus_BitmapApplyFilter_Median($hImage, 4) ConsoleWrite(Round(TimerDiff($t) / 1000, 2) & " s / " & Round(TimerDiff($t) / 60000, 2) & " min" & @CRLF) Global Const $iPic = GUICtrlCreatePic("", 0, 0, $iW - 1, $iH - 1) Global Const $iPic_o = GUICtrlCreatePic("", $iW, 0, $iW - 1, $iH - 1) _WinAPI_DeleteObject(GUICtrlSendMsg($iPic, $STM_SETIMAGE, $IMAGE_BITMAP, $hGDIBitmap)) Global Const $hGDIBitmap2 = _GDIPlus_BitmapCreateHBITMAPFromBitmap($hImage) _WinAPI_DeleteObject(GUICtrlSendMsg($iPic_o, $STM_SETIMAGE, $IMAGE_BITMAP, $hGDIBitmap2)) GUISetState() AdlibUnRegister("Progress") ToolTip("") Do Until GUIGetMsg() = -3 _GDIPlus_ImageDispose($hImage) _WinAPI_DeleteObject($hGDIBitmap) _WinAPI_DeleteObject($hGDIBitmap2) _GDIPlus_Shutdown() Exit Func Progress() ToolTip(Int($fProg / $iEnd * 100) & " % / " & Round(TimerDiff($t) / 60000, 2) & " min", MouseGetPos(0) + 30, MouseGetPos(1) + 30) EndFunc #Region Symmetric Nearest Neighbour Func _GDIPlus_BitmapApplyFilter_SymmetricNearestNeighbour($hImage, $fRadius = 2, $bGDI = True) ;no alpha channel implemented yet Local Const $iW = _GDIPlus_ImageGetWidth($hImage), $iH = _GDIPlus_ImageGetHeight($hImage) Local Const $hBitmap_Dest = _GDIPlus_BitmapCreateFromScan0($iW, $iH) Local Const $tBitmapData_Dest = _GDIPlus_BitmapLockBits($hBitmap_Dest, 0, 0, $iW - 1, $iH - 1, $GDIP_ILMWRITE, $GDIP_PXF32ARGB) Local Const $iScan0_Dest = DllStructGetData($tBitmapData_Dest, "Scan0") Local Const $tPixel_Dest = DllStructCreate("int[" & $iW * $iH & "];", $iScan0_Dest) Local Const $tBitmapData = _GDIPlus_BitmapLockBits($hImage, 0, 0, $iW - 1, $iH - 1, $GDIP_ILMREAD, $GDIP_PXF32ARGB) Local Const $iScan0 = DllStructGetData($tBitmapData, "Scan0") Local Const $tPixel = DllStructCreate("int[" & $iW * $iH & "];", $iScan0) Local $iRowOffset, $iX, $iY, $c, $k, $sumR, $sumG, $sumB, $iCount, $xx, $yy, $iR, $iG, $iB, $iR1, $iG1, $iB1, $iR2, $iG2, $iB2, $x, $y For $iY = 0 To $iH - 1 $iRowOffset = $iY * $iW For $iX = 0 To $iW - 1 $sumR = 0 $sumG = 0 $sumB = 0 $iCount = 0 $c = DllStructGetData($tPixel, 1, $iRowOffset + $iX) $iR = BitShift(BitAND(0x00FF0000, $c), 16) $iG = BitShift(BitAND(0x0000FF00, $c), 8) $iB = BitAND(0x000000FF, $c) For $yy = -$fRadius To $fRadius For $xx = -$fRadius To $fRadius $k = $iX + $xx $x = $k < 0 ? 0 : $k > $iW - 1 ? $iW - 1 : $k $k = $iY + $yy $y = $k < 0 ? 0 : $k > $iH - 1 ? $iH - 1 : $k $c = DllStructGetData($tPixel, 1, $y * $iW + $x) $iR1 = BitShift(BitAND(0x00FF0000, $c), 16) $iG1 = BitShift(BitAND(0x0000FF00, $c), 8) $iB1 = BitAND(0x000000FF, $c) $k = $iX - $xx $x = $k < 0 ? 0 : $k > $iW - 1 ? $iW - 1 : $k $k = ($iY - $yy) $y = $k < 0 ? 0 : $k > $iH - 1 ? $iH - 1 : $k $c = DllStructGetData($tPixel, 1, $y * $iW + $x) $iR2 = BitShift(BitAND(0x00FF0000, $c), 16) $iG2 = BitShift(BitAND(0x0000FF00, $c), 8) $iB2 = BitAND(0x000000FF, $c) If __DeltaE($iR, $iG, $iB, $iR1, $iG1, $iB1) < __DeltaE($iR, $iG, $iB, $iR2, $iG2, $iB2) Then $sumR += $iR1 $sumG += $iG1 $sumB += $iB1 Else $sumR += $iR2 $sumG += $iG2 $sumB += $iB2 EndIf $iCount += 1 Next Next DllStructSetData($tPixel_Dest, 1, 0xFF000000 + Int($sumR / $iCount) * 0x10000 + Int($sumG / $iCount) * 0x100 + Int($sumB / $iCount), $iRowOffset + $iX) $fProg += 1 Next Next _GDIPlus_BitmapUnlockBits($hImage, $tBitmapData) _GDIPlus_BitmapUnlockBits($hBitmap_Dest, $tBitmapData_Dest) _GDIPlus_ImageSaveToFile($hBitmap_Dest, @ScriptDir & "\Filter_SNN" & $fRadius & "_" & @YEAR & @MON & @MDAY & @MIN & @SEC & ".png") If $bGDI Then Local $hGDIBitmap = _GDIPlus_BitmapCreateHBITMAPFromBitmap($hBitmap_Dest) _GDIPlus_BitmapDispose($hBitmap_Dest) Return $hGDIBitmap EndIf Return $hBitmap_Dest EndFunc Func __DeltaE($iR1, $iG1, $iB1, $iR2, $iG2, $iB2) Return Sqrt(($iR1 - $iR2) * ($iR1 - $iR2) + ($iG1 - $iG2) * ($iG1 - $iG2) + ($iB1 - $iB2) * ($iB1 - $iB2)) EndFunc #EndRegion #Region Jitter Func _GDIPlus_BitmapApplyFilter_Jitter($hImage, $iAmount = 20, $bGDI = True) Local Const $iW = _GDIPlus_ImageGetWidth($hImage), $iH = _GDIPlus_ImageGetHeight($hImage) Local Const $hBitmap_Dest = _GDIPlus_BitmapCreateFromScan0($iW, $iH) Local Const $tBitmapData_Dest = _GDIPlus_BitmapLockBits($hBitmap_Dest, 0, 0, $iW - 1, $iH - 1, $GDIP_ILMWRITE, $GDIP_PXF32ARGB) Local Const $iScan0_Dest = DllStructGetData($tBitmapData_Dest, "Scan0") Local Const $tPixel_Dest = DllStructCreate("int[" & $iW * $iH & "];", $iScan0_Dest) Local Const $tBitmapData = _GDIPlus_BitmapLockBits($hImage, 0, 0, $iW - 1, $iH - 1, $GDIP_ILMREAD, $GDIP_PXF32ARGB) Local Const $iScan0 = DllStructGetData($tBitmapData, "Scan0") Local Const $tPixel = DllStructCreate("int[" & $iW * $iH & "];", $iScan0) Local $iX, $iY, $iRowOffset, $fNX, $fNY For $iY = 0 To $iH - 1 $iRowOffset = $iY * $iW + 1 For $iX = 0 To $iW - 1 $fNX = $iX + Int((Random() - 0.5) * $iAmount) $fNX = $fNX < 1 ? 1 : $fNX > $iW - 1 ? $iW - 1 : $fNX $fNY = ($iY + Int((Random() - 0.5) * $iAmount)) $fNY = $fNY < 1 ? 1 : $fNY > $iH - 1 ? $iH - 1 : $fNY $fNY *= $iW DllStructSetData($tPixel_Dest, 1, DllStructGetData($tPixel, 1, $fNY + $fNX), $iRowOffset + $iX) $fProg += 1 Next Next _GDIPlus_BitmapUnlockBits($hImage, $tBitmapData) _GDIPlus_BitmapUnlockBits($hBitmap_Dest, $tBitmapData_Dest) _GDIPlus_ImageSaveToFile($hBitmap_Dest, @ScriptDir & "\Filter_Jitter" & $iAmount & "_" & @YEAR & @MON & @MDAY & @MIN & @SEC & ".png") If $bGDI Then Local $hGDIBitmap = _GDIPlus_BitmapCreateHBITMAPFromBitmap($hBitmap_Dest) _GDIPlus_BitmapDispose($hBitmap_Dest) Return $hGDIBitmap EndIf Return $hBitmap_Dest EndFunc #EndRegion #Region Median Func _GDIPlus_BitmapApplyFilter_Median($hImage, $fRadius = 3, $bGDI = True) Local Const $iW = _GDIPlus_ImageGetWidth($hImage), $iH = _GDIPlus_ImageGetHeight($hImage) Local Const $hBitmap_Dest = _GDIPlus_BitmapCreateFromScan0($iW, $iH) Local Const $tBitmapData_Dest = _GDIPlus_BitmapLockBits($hBitmap_Dest, 0, 0, $iW - 1, $iH - 1, $GDIP_ILMWRITE, $GDIP_PXF32ARGB) Local Const $iScan0_Dest = DllStructGetData($tBitmapData_Dest, "Scan0") Local Const $tPixel_Dest = DllStructCreate("int[" & $iW * $iH & "];", $iScan0_Dest) Local Const $tBitmapData = _GDIPlus_BitmapLockBits($hImage, 0, 0, $iW - 1, $iH - 1, $GDIP_ILMREAD, $GDIP_PXF32ARGB) Local Const $iScan0 = DllStructGetData($tBitmapData, "Scan0") Local Const $tPixel = DllStructCreate("int[" & $iW * $iH & "];", $iScan0) Local $iX, $iY, $iRowOffset For $iY = 0 To $iH - 1 $iRowOffset = $iY * $iW + 1 For $iX = 0 To $iW - 1 DllStructSetData($tPixel_Dest, 1, __Median_Value($iX, $iY, $fRadius, $tPixel, $iW, $iH), $iRowOffset + $iX) $fProg += 1 Next Next _GDIPlus_BitmapUnlockBits($hImage, $tBitmapData) _GDIPlus_BitmapUnlockBits($hBitmap_Dest, $tBitmapData_Dest) _GDIPlus_ImageSaveToFile($hBitmap_Dest, @ScriptDir & "\Filter_Median" & $fRadius & "_" & @YEAR & @MON & @MDAY & @MIN & @SEC & ".png") If $bGDI Then Local $hGDIBitmap = _GDIPlus_BitmapCreateHBITMAPFromBitmap($hBitmap_Dest) _GDIPlus_BitmapDispose($hBitmap_Dest) Return $hGDIBitmap EndIf Return $hBitmap_Dest EndFunc Func __Median_Value($iPosX, $iPosY, $fRadius, $tPixel, $iW, $iH) Local $iX, $iY, $aColors[1000], $iColors = 0, $iSize = $iW * $iH - 1, $iOff, $e For $iX = $iPosX - $fRadius To $iPosX + $fRadius For $iY = $iPosY - $fRadius To $iPosY + $fRadius $iOff = 1 + $iY * $iW + $iX $aColors[$iColors] = DllStructGetData($tPixel, 1, $iOff < 1 ? 1 : $iOff > $iSize ? $iSize : $iOff) $iColors += 1 Next Next ReDim $aColors[$iColors] ;~ _ArraySort($aColors, 0) $e = $iColors - 1 __ArrayQuickSort1D($aColors, 0, $e) Local $iMid = Floor($iColors / 2), $iMedian If BitAND($iColors, 1) Then $iMedian = Int($aColors[$iMid + 1]) Else $iMedian = Int(($aColors[$iMid] + $aColors[$iMid + 1]) / 2) EndIf Return $iMedian EndFunc #EndRegion  
    • mjolnirmarkiv
      By mjolnirmarkiv
      Hi!
      Is there any way to use .NET DLL libraries with AutoIt? I happen to have one that'd have made my life easier, but DLLCall() returns an error: no functions with such name found. Searching and reading forums made me think that's not a fault of a library. I've used yashied's DLL Helper, but it didn't return any function names as well.
      Thanks!