Jump to content

How to create a captcha wit autoit?


fielmann
 Share

Recommended Posts

Hi,

just create a little GUI with a few buttons and then randomize the text.

Mega

Scripts & functions Organize Includes Let Scite organize the include files

Yahtzee The game "Yahtzee" (Kniffel, DiceLion)

LoginWrapper Secure scripts by adding a query (authentication)

_RunOnlyOnThis UDF Make sure that a script can only be executed on ... (Windows / HD / ...)

Internet-Café Server/Client Application Open CD, Start Browser, Lock remote client, etc.

MultipleFuncsWithOneHotkey Start different funcs by hitting one hotkey different times

Link to comment
Share on other sites

Hi,

just create a little GUI with a few buttons and then randomize the text.

Mega

Here's a little example

#include <date.au3>
#include <GUIConstantsEx.au3>
#include <windowsconstants.au3>
#include <ScreenCapture.au3>
Dim $fonts[4] = ["MS Sans Serif", "Arial", "Times New Roman", "Lucida Console"]
Dim $colours[3] = [0xff0000, 0x00ff00, 0x0000ff]
$g = GUICreate("captcha")
Dim $lab[4]
$ip = GUICtrlCreateInput("", 30, 200)
$tlwid = 0
$top = 0
$left = 0
$width = 9999
$height = 0
$code = ""
For $n = 0 To UBound($fonts) - 1
    GUISetFont(Random(12, 26, 1), 400, 0, $fonts[Random(0, UBound($fonts) - 1, 1)])
    $letter = Chr(Random(Asc("A"), Asc("Z"), 1))
    $code &= $letter
    $l1 = GUICtrlCreateLabel($letter, 10 + $tlwid + Random(0, 12, 1), 15 + Random(0, 20, 1))
    GUICtrlSetBkColor(-1, 0xffffff);$GUI_BKCOLOR_TRANSPARENT )
    GUICtrlSetColor(-1, $colours[Random(0, 2, 1)])
    $lwid = ControlGetPos("captcha", "", $l1)
    If $top > $lwid[1] Then $top = $lwid[1]
    If $left > $lwid[0] Then $left = $lwid[0]
    $width = $lwid[2] + $lwid[0]
    If $height < $lwid[3] + $lwid[1] Then $height = $lwid[3] + $lwid[1]

    $tlwid += $lwid[2]
Next
$wp = WinGetPos("captcha")


GUICtrlCreateLabel("", $left, $top, $width, $height, $WS_CLIPSIBLINGS)
GUICtrlSetBkColor(-1, 0xffffff)
GUISetState()


;get height of title bar
Savecaptcha()

GUICtrlSetData($ip, $code)
While GUIGetMsg() <> -3
WEnd

Func Savecaptcha()
    Const $SM_CXFIXEDFRAME = 7;, $SM_CXVSCROLL = 2,Const $SM_CYCAPTION = 4
    $wtitle = DllCall('user32.dll', 'int', 'GetSystemMetrics', 'int', $SM_CYCAPTION)
    $wtitle = $wtitle[0]
    $wside = DllCall('user32.dll', 'int', 'GetSystemMetrics', 'int', $SM_CXFIXEDFRAME)
    $wside = $wside[0]
    _ScreenCapture_Capture("cptcha1.jpg", $wp[0] + $wside, $wp[1] + $wtitle + $wside, $wp[0] + $wside + $width, $wp[1] + $wtitle + $wside + $height)
EndFunc  ;==>Savecaptcha

EDIT: Added saving captcha as a jpg.

Edited by martin
Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

Try this:

#include <WindowsConstants.au3>
#include <GDIPlus.au3>
#include <ScreenCapture.au3>
;

$sImage_Path = @ScriptDir & '\Captcha.png'
$sRandom_Captcha = _Get_Random_Captcha(4)

_GDIPlus_ImageCaptchaCreate($sImage_Path, $sRandom_Captcha, 0xFF0000, 36, 4)

; Show image
Run('MSPaint.exe "' & $sImage_Path & '"')

Func _GDIPlus_ImageCaptchaCreate($sImage_Path, $sCaptcha, $iColor=0xFF0000, $iFontSize=36, $iFormat=4)
    ; Initialize GDI+ library
    _GDIPlus_StartUp()
    
    ;There must be some other methods to create an empty image, but this is the only one i figured out :)
    Local $hGUI                     = GUICreate("", 220, 100, -1, -1, $WS_POPUP)
    
    GUISetBkColor(0xFFFFFF, $hGUI)
    GUISetState(@SW_SHOW,   $hGUI)
    
    Local $hBitmap                  = _ScreenCapture_CaptureWnd("", $hGUI, 0, 0, -1, -1, 0)
    Local $hImage                   = _GDIPlus_BitmapCreateFromHBITMAP($hBitmap)
    
    GUIDelete($hGUI)
    
    Local $hGraphic                 = _GDIPlus_ImageGetGraphicsContext($hImage)
    Local $hFamily                  = _GDIPlus_FontFamilyCreate("Arial")
    Local $hFont                    = _GDIPlus_FontCreate($hFamily, $iFontSize, 1)
    Local $tLayout                  = _GDIPlus_RectFCreate(0, 0)
    Local $hFormat                  = _GDIPlus_StringFormatCreate($iFormat)
    Local $hBrush1                  = _GDIPlus_BrushCreateSolid(0xA2FFFFFF)
    Local $hBrush2                  = _GDIPlus_BrushCreateSolid("0xC4" & Hex(Number($iColor), 6))
    Local $hPen                     = _GDIPlus_PenCreate(0xC4000000, 2)
    Local $aInfo                    = _GDIPlus_GraphicsMeasureString($hGraphic, $sCaptcha, $hFont, $tLayout, $hFormat)
    
    Local $iWidth                   = DllStructGetData($aInfo[0], "Width")
    Local $iHeight                  = DllStructGetData($aInfo[0], "Height")
    
    Local $iImage_Width             = _GDIPlus_ImageGetWidth($hImage)
    Local $iImage_Height            = _GDIPlus_ImageGetHeight($hImage)
    
    Local $iLeft                    = ($iImage_Width / 2) - ($iWidth / 2)
    Local $iTop                     = ($iImage_Height / 2) - ($iHeight / 2)
    
    DllStructSetData($aInfo[0], "X", $iLeft)
    DllStructSetData($aInfo[0], "Y", $iTop)
    
    ;Uncomment these two lines to set frame for the captcha text
    ;_GDIPlus_GraphicsFillRect($hGraphic, $iLeft, $iTop, $iWidth, $iHeight, $hBrush1)
    ;_GDIPlus_GraphicsDrawRect($hGraphic, $iLeft, $iTop, $iWidth, $iHeight, $hPen)
    
    _GDIPlus_GraphicsFillRect($hGraphic, 1, 1, $iImage_Width-2, $iImage_Height-2, $hBrush1)
    _GDIPlus_GraphicsDrawRect($hGraphic, 1, 1, $iImage_Width-2, $iImage_Height-2, $hPen)
    
    _GDIPlus_GraphicsDrawStringEx($hGraphic, $sCaptcha, $hFont, $aInfo[0], $hFormat, $hBrush2)
    
    ; Save image
    _GDIPlus_ImageSaveToFile($hImage, $sImage_Path)
    
    ; Free resources
    _GDIPlus_PenDispose         ($hPen    )
    _GDIPlus_BrushDispose       ($hBrush1 )
    _GDIPlus_BrushDispose       ($hBrush2 )
    _GDIPlus_StringFormatDispose($hFormat )
    _GDIPlus_FontDispose        ($hFont   )
    _GDIPlus_FontFamilyDispose  ($hFamily )
    _GDIPlus_GraphicsDispose    ($hGraphic)
    _GDIPlus_ImageDispose       ($hImage  )
    
    _GDIPlus_ShutDown()
EndFunc

Func _Get_Random_Captcha($iChars_Num=4)
    Local $sRet_Captcha = '', $iRandom_Char, $iExitLoop
    
    For $i = 1 To $iChars_Num
        $iExitLoop = False
        
        While 1
            $iRandom_Char = Random(49, 99, 1)
            
            Switch $iRandom_Char
                Case Asc("a") To Asc("z"), Asc("A") To Asc("Z"), Asc("0") To Asc("9")
                    ExitLoop
            EndSwitch
        WEnd
        
        $sRet_Captcha &= Chr($iRandom_Char)
    Next
    
    Return $sRet_Captcha
EndFunc

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

Hello there.

MrCreator, that's great example :)

Thanx :).

Here's a little example

...Code cuted...

EDIT: Added saving captcha as a jpg.

Hi martin, nice idea, here is a modified version of it, i made a “Captcha Generator” from it o:)

#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <ScreenCapture.au3>

Global $aFonts[4] = ["MS Sans Serif", "Arial", "Times New Roman", "Lucida Console"]
Global $aColours[3] = [0xFF0000, 0x00FF00, 0x0000FF]

Global $hGUI, $Captcha_Input, $Generate_Button, $SaveCaptcha_Button, $Background_Label


$hGUI = GUICreate("Captcha Generator Demo", 250, 250)

$Captcha_Input = GUICtrlCreateInput("", 20, 170, 70, 20)
$Generate_Button = GUICtrlCreateButton("Generate", 20, 200, 70, 20)

$SaveCaptcha_Button = GUICtrlCreateButton("Save to file...", 120, 200, 120, 20)

_Generate_Captcha()
GUISetState()

While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
        Case $Generate_Button
            _Generate_Captcha()
        Case $SaveCaptcha_Button
            $sCaptcha_File = FileSaveDialog("Save Captcha as...", "", "Image Files (*.png;*.jpg;*.bmp)", 18, "Captcha.png", $hGUI)
            If @error Then ContinueLoop
            
            If Not StringRegExp($sCaptcha_File, ".*\.png|\.jpg|\.bmp$") Then $sCaptcha_File &= ".png"
            
            _ScreenCapture_CaptureWnd($sCaptcha_File, GUICtrlGetHandle($Background_Label), 0, 0, -1, -1, 0)
    EndSwitch
WEnd

Func _Generate_Captcha()
    For $i = $SaveCaptcha_Button+1 To _GUIGetLastCtrlID()
        GUICtrlDelete($i)
    Next
    
    Local $Label, $aLabel_Pos, $iLabel_Left = 0, $iTop = 10, $iLeft = 10, $iWidth = 9999, $iHeight = 0, $sLetter = "", $sCode = ""
    
    For $n = 0 To UBound($aFonts) - 1
        GUISetFont(Random(12, 26, 1), 400, 0, $aFonts[Random(0, UBound($aFonts) - 1, 1)])
        
        $sLetter = Chr(Random(Asc("A"), Asc("Z"), 1))
        $sCode &= $sLetter
        
        $Label = GUICtrlCreateLabel($sLetter, 45 + $iLabel_Left, 40)
        GUICtrlSetBkColor(-1, 0xFFFFFF)
        GUICtrlSetColor(-1, $aColours[Random(0, 2, 1)])
        
        $aLabel_Pos = ControlGetPos($hGUI, "", $Label)
        
        If $iTop > $aLabel_Pos[1] Then $iTop = $aLabel_Pos[1]
        If $iLeft > $aLabel_Pos[0] Then $iLeft = $aLabel_Pos[0]
        
        $iWidth = $aLabel_Pos[2] + $aLabel_Pos[0]
        If $iHeight < $aLabel_Pos[3] + $aLabel_Pos[1] Then $iHeight = $aLabel_Pos[3] + $aLabel_Pos[1]
        
        $iLabel_Left += $aLabel_Pos[2]
    Next

    $Background_Label = GUICtrlCreateLabel("", $iLeft, $iTop, $iWidth+10, $iHeight+10, _
        $WS_CLIPSIBLINGS, $WS_EX_DLGMODALFRAME+$WS_EX_CLIENTEDGE )
    GUICtrlSetBkColor(-1, 0xFFFFFF)
    
    GUICtrlSetData($Captcha_Input, $sCode)
EndFunc

Func _GUIGetLastCtrlID()
    Local $aRet = DllCall("user32.dll", "int", "GetDlgCtrlID", "hwnd", GUICtrlGetHandle(-1))
    
    Return $aRet[0]
EndFunc

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

Thanx :).

Hi martin, nice idea, here is a modified version of it, i made a Captcha Generator from it :)

....

Yes, that's a better and neater version, thanks MrCreator, you're very good at making my attempts tidy. I didn't think of using the label handle for the screen capture but it's much simpler that way.

I didn't allow for many characters so here's a small improvement.

#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <ScreenCapture.au3>

Global $aFonts[4] = ["MS Sans Serif", "Arial", "Times New Roman", "Lucida Console"]
Global $aColours[3] = [0xFF0000, 0x00FF00, 0x0000FF]

Global $hGUI, $Captcha_Input, $Generate_Button, $SaveCaptcha_Button, $Background_Label


$hGUI = GUICreate("Captcha Generator Demo", 250, 250)

$Captcha_Input = GUICtrlCreateInput("", 20, 170, 70, 20)
$Generate_Button = GUICtrlCreateButton("Generate", 20, 200, 70, 20)

$SaveCaptcha_Button = GUICtrlCreateButton("Save to file...", 120, 200, 120, 20)

_Generate_Captcha()
GUISetState()

While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
        Case $Generate_Button
            _Generate_Captcha()
        Case $SaveCaptcha_Button
            $sCaptcha_File = FileSaveDialog("Save Captcha as...", "", "Image Files (*.png;*.jpg;*.bmp)", 18, "Captcha.png", $hGUI)
            If @error Then ContinueLoop
           
            If Not StringRegExp($sCaptcha_File, ".*\.png|\.jpg|\.bmp$") Then $sCaptcha_File &= ".png"
           
            _ScreenCapture_CaptureWnd($sCaptcha_File, GUICtrlGetHandle($Background_Label), 0, 0, -1, -1, 0)
    EndSwitch
WEnd

Func _Generate_Captcha()
    
    For $i = $SaveCaptcha_Button+1 To _GUIGetLastCtrlID()
        GUICtrlDelete($i)
    Next
   
    Local $Label, $aLabel_Pos, $iLabel_Left = 0, $iTop = 10, $iLeft = 10, $iWidth = 9999, $iHeight = 0, $sLetter = "", $sCode = ""
    Local $charList = StringSplit("abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789","")
   
    For $n = 0 To UBound($aFonts) - 1
        GUISetFont(Random(12, 26, 1), 400, 0, $aFonts[Random(0, UBound($aFonts) - 1, 1)])
       
       ;$sLetter = Chr(Random(Asc("A"), Asc("Z"), 1))
        $sLetter = $charList[Random(1,$charlist[0],1)]
        $sCode &= $sLetter
       
        $Label = GUICtrlCreateLabel($sLetter, 45 + $iLabel_Left, 40)
        GUICtrlSetBkColor(-1, 0xFFFFFF)
        GUICtrlSetColor(-1, $aColours[Random(0, 2, 1)])
       
        $aLabel_Pos = ControlGetPos($hGUI, "", $Label)
       
        If $iTop > $aLabel_Pos[1] Then $iTop = $aLabel_Pos[1]
        If $iLeft > $aLabel_Pos[0] Then $iLeft = $aLabel_Pos[0]
       
        $iWidth = $aLabel_Pos[2] + $aLabel_Pos[0]
        If $iHeight < $aLabel_Pos[3] + $aLabel_Pos[1] Then $iHeight = $aLabel_Pos[3] + $aLabel_Pos[1]
       
        $iLabel_Left += $aLabel_Pos[2]
    Next

    $Background_Label = GUICtrlCreateLabel("", $iLeft, $iTop, $iWidth+10, $iHeight+10, _
        $WS_CLIPSIBLINGS, $WS_EX_DLGMODALFRAME+$WS_EX_CLIENTEDGE )
    GUICtrlSetBkColor(-1, 0xFFFFFF)
   
    GUICtrlSetData($Captcha_Input, $sCode)
EndFunc

Func _GUIGetLastCtrlID()
    Local $aRet = DllCall("user32.dll", "int", "GetDlgCtrlID", "hwnd", GUICtrlGetHandle(-1))
   
    Return $aRet[0]
EndFunc
Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

I had to see if this could be done.

This is a cut down version of the script at

http://www.autoitscript.com/forum/index.ph...st&p=584436

with the controls copied from previous posts this thread.

Edit:30/11/2008 Added _AntiAlias() for smoother lines. And made $iW and $iH Global as per Martin's suggestion

#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <StaticConstants.au3>
#include <GDIPlus.au3>
#include <WinAPI.au3>
#include<Color.au3>

Opt("GUIOnEventMode", 1) ;0=disabled, 1=OnEvent mode enabled

Global $aFonts[4] = ["MS Sans Serif", "Arial", "Times New Roman", "Lucida Console"]
Global $charList = StringSplit("abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789", "")
Global $aColours[4] = [0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0xFFFFFF00]
Global $ApW = 250, $ApH = 250, $iW = 150, $iH = 100
Global $Button[1], $Pic, $sCode, $hImage
Global Const $iPI = 3.1415926535897932384626433832795

$hGui = GUICreate("A GDIPlus CAPTCHA", $ApW, $ApH)
GUISetOnEvent(-3, "_Quit")
GUISetBkColor(0xffA0A0, $hGui)

$Background_Label = GUICtrlCreateLabel("", 15, 15, $iW +10, $iH +10, $WS_CLIPSIBLINGS, BitOR($WS_EX_DLGMODALFRAME, $WS_EX_CLIENTEDGE))
$Pic = GUICtrlCreatePic("", 20, 20, $iW, $iH)
GUICtrlSetState(-1, $GUI_DISABLE)

$Captcha_Input = GUICtrlCreateInput("", 20, 170, 70, 20)
$Generate_Button = GUICtrlCreateButton("Generate", 20, 200, 70, 20)
GUICtrlSetOnEvent($Generate_Button, "PicSetGraphics")
$SaveCaptcha_Button = GUICtrlCreateButton("Save to file...", 120, 200, 120, 20)
GUICtrlSetOnEvent($SaveCaptcha_Button, "Save")

_GDIPlus_Startup()
PicSetGraphics(); <-- Draw GDIPlus graphics on Picture control.

GUISetState(@SW_SHOW, $hGui)

While 1
    Sleep(10)
WEnd
_GDIPlus_Shutdown()

Func PicSetGraphics()
    Local Const $STM_SETIMAGE = 0x0172
    Local Const $IMAGE_BITMAP = 0
    Local $hWnd, $hBitmap, $hGraphic, $hBrush, $hBrush1, $hbmp, $aBmp, $sCode = ""

    $hWnd = GUICtrlGetHandle($Pic)
    If $hImage > 0 Then _GDIPlus_ImageDispose($hImage)

    ;Buffer
    $hBitmap = _WinAPI_CreateSolidBitmap($hGui, 0x8FAAAAAA, $iW, $iH) ;
    $hImage = _GDIPlus_BitmapCreateFromHBITMAP($hBitmap)
    $hGraphic = _GDIPlus_ImageGetGraphicsContext($hImage)
    _AntiAlias($hGraphic)
    ;----->  All Graphics Here

    ;Rainbow background
    For $x = 0 To $iW
        $hue = Color_SetHSL(Int($x / 2))
        $hPen1 = _GDIPlus_PenCreate("0x80" & Hex($hue, 6), 1) ; Slightly transparent
        _GDIPlus_GraphicsDrawLine($hGraphic, $x, 0, $x, $ApH, $hPen1)
        _GDIPlus_PenDispose($hPen1)
    Next

    For $x = 0 To 3

        ;Draw random Lines
        $hPen1 = _GDIPlus_PenCreate("0x" & Hex($aColours[Random(0, 3, 1)], 8), Random(1, 3, 1))
        _GDIPlus_GraphicsDrawLine($hGraphic, Random(0, $iW, 1), Random(0, 5, 1), Random(0, $iW, 1), _
                Random($iH - 5, $iH, 1), $hPen1)
        $hPen1 = _GDIPlus_PenCreate("0x" & Hex($aColours[Random(0, 3, 1)], 8), Random(1, 3, 1))
        _GDIPlus_GraphicsDrawLine($hGraphic, Random(0, 5, 1), Random(0, $iH, 1), Random($iW - 5, $iW, 1), _
                Random(0, $iH, 1), $hPen1)
        _GDIPlus_PenDispose($hPen1)

        ; Draw a character
        $sLetter = $charList[Random(1, $charList[0], 1)]
        GUISetFont(Random(14, 26, 1), 400, 0, $aFonts[Random(0, UBound($aFonts) - 1, 1)])
        $iBy = $x * ($iW / 4)
        GDIPlus_SetAngledText($hGraphic, $sLetter, Random($iBy + 15, $iBy + ($iW / 4) - 15, 1), _
                Random(($iH / 2) - 15, ($iH / 2) + 5, 1), Random(-30, 30, 1), "", 16, "0x" & Hex($aColours[Random(0, 3, 1)], 8))
        $sCode &= $sLetter

    Next

    ; -----> End of all Graphics

    GUICtrlSetData($Captcha_Input, $sCode)

    ; Keeps all GDIPlus graphics visible
    $hbmp = _GDIPlus_BitmapCreateHBITMAPFromBitmap($hImage)
    $aBmp = DllCall("user32.dll", "hwnd", "SendMessage", "hwnd", $hWnd, "int", $STM_SETIMAGE, "int", $IMAGE_BITMAP, "int", $hbmp)
    _WinAPI_RedrawWindow($hGui, "", "", BitOR($RDW_INVALIDATE, $RDW_UPDATENOW, $RDW_FRAME))

    If $aBmp[0] <> 0 Then _WinAPI_DeleteObject($aBmp[0])

    _GDIPlus_BrushDispose($hBrush)
    _GDIPlus_PenDispose($hPen1)
    _GDIPlus_GraphicsDispose($hGraphic)
    _WinAPI_DeleteObject($hbmp)
    _WinAPI_DeleteObject($hBitmap)
EndFunc   ;==>PicSetGraphics


Func Save()
    $sCaptcha_File = FileSaveDialog("Save Captcha as...", "", "Image Files (*.png;*.jpg;*.bmp)", 18, "Captcha.jpg", $hGui)
    If @error Then Return

    If Not StringRegExp($sCaptcha_File, ".*\.png|\.jpg|\.bmp$") Then $sCaptcha_File &= ".jpg"
    ConsoleWrite(" Saved  " & $sCaptcha_File & @CRLF)
    _GDIPlus_ImageSaveToFile($hImage, $sCaptcha_File)
    _GDIPlus_ImageDispose($hImage)
EndFunc   ;==>Save

; #FUNCTION# ================================================================
; Name...........: GDIPlus_SetAngledText
; Description ...: Adds text to a graphic object at any angle.
; Syntax.........: GDIPlus_SetAngledText($hGraphic, $nText, [$iCentreX, [$iCentreY, [$iAngle , [$nFontName , _
;                              [$nFontSize, [$iARGB, [$iAnchor]]]]]]] )
; Parameters ....: $hGraphic   - The Graphics object to receive the added text.
;               $nText      - Text string to be displayed
;                  $iCentreX       - Horizontal coordinate of horixontal centre of the text rectangle        (default =  0 )
;                  $iCentreY        - Vertical coordinate of vertical centre of the text rectangle             (default = 0 )
;                  $iAngle     - The angle which the text will be place in degrees.         (default = "" or blank = 0 )
;                  $nFontName  - The name of the font to be used                      (default = "" or Blank = "Arial" )
;                  $nFontSize  - The font size to be used                                  (default = "" or Blank = 12 )
;                  $iARGB      - Alpha(Transparency), Red, Green and Blue color (0xAARRGGBB) (Default= "" = random color
;                                                                                      or Default = Blank = 0xFFFF00FF )
;               $iAnchor    - If zero (default) positioning $iCentreX, $iCentreY values refer to centre of text string.
;                                If not zero positioning $iCentreX, $iCentreY values refer to top left corner of text string.
; Return values .: 1
; Author ........: Malkey
; Modified.......:
; Remarks .......: Call _GDIPlus_Startup() before starting this function, and call _GDIPlus_Shutdown()after function ends.
;                  Can enter calculation for Angle Eg. For incline, -ATan($iVDist / $iHDist) * 180 / $iPI , where
;               $iVDist is Vertical Distance,  $iHDist is Horizontal Distance, and, $iPI is Pi, (an added Global Const).
;               When used with other graphics, call this function last. The MatrixRotate() may affect following graphics.
; Related .......: _GDIPlus_Startup(), _GDIPlus_Shutdown(), _GDIPlus_GraphicsDispose($hGraphic)
; Link ..........;
; Example .......; Yes
; ========================================================================================
Func GDIPlus_SetAngledText($hGraphic, $nText, $iCentreX = 0, $iCentreY = 0, $iAngle = 0, $nFontName = "Arial", _
        $nFontSize = 12, $iARGB = 0xFFFF00FF, $iAnchor = 0)
    Local $x, $y, $iX, $iY, $iWidth, $iHeight
    Local $hMatrix, $iXt, $iYt, $hBrush, $hFormat, $hFamily, $hFont, $tLayout

    ; Default values
    If $iAngle = "" Then $iAngle = 0
    If $nFontName = "" Or $nFontName = -1 Then $nFontName = "Arial" ; "Microsoft Sans Serif"
    If $nFontSize = "" Then $nFontSize = 12
    If $iARGB = "" Then ; Randomize ARGB color
        $iARGB = "0xFF" & Hex(Random(0, 255, 1), 2) & Hex(Random(0, 255, 1), 2) & Hex(Random(0, 255, 1), 2)
    EndIf

    $hFormat = _GDIPlus_StringFormatCreate(0)
    $hFamily = _GDIPlus_FontFamilyCreate($nFontName)
    $hFont = _GDIPlus_FontCreate($hFamily, $nFontSize, 1, 3)
    $tLayout = _GDIPlus_RectFCreate($iCentreX, $iCentreY, 0, 0)
    $aInfo = _GDIPlus_GraphicsMeasureString($hGraphic, $nText, $hFont, $tLayout, $hFormat)
    $iWidth = Ceiling(DllStructGetData($aInfo[0], "Width"))
    $iHeight = Ceiling(DllStructGetData($aInfo[0], "Height"))

    ;Later calculations based on centre of Text rectangle.
    If $iAnchor = 0 Then ; Reference to middle of Text rectangle
        $iX = $iCentreX
        $iY = $iCentreY
    Else ; Referenced centre point moved to top left corner of text string.
        $iX = $iCentreX + (($iWidth - Abs($iHeight * Sin($iAngle * $iPI / 180))) / 2)
        $iY = $iCentreY + (($iHeight + Abs($iWidth * Sin($iAngle * $iPI / 180))) / 2)
    EndIf

    ;Rotation Matrix
    $hMatrix = _GDIPlus_MatrixCreate()
    _GDIPlus_MatrixRotate($hMatrix, $iAngle, 1)
    _GDIPlus_GraphicsSetTransform($hGraphic, $hMatrix)

    ;x, y are display coordinates of center of width and height of the rectanglular text box.
    ;Top left corner coordinates rotate in a circular path with radius = (width of text box)/2.
    ;Parametric equations for a circle, and adjustments for centre of text box
    $x = ($iWidth / 2) * Cos($iAngle * $iPI / 180) - ($iHeight / 2) * Sin($iAngle * $iPI / 180)
    $y = ($iWidth / 2) * Sin($iAngle * $iPI / 180) + ($iHeight / 2) * Cos($iAngle * $iPI / 180)

    ;Rotation of Coordinate Axes formulae - To display at x and y after rotation, we need to enter the
    ;x an y position values of where they rotated from. This is done by rotating the coordinate axes.
    ;Use $iXt, $iYt in  _GDIPlus_RectFCreate. These x, y values is the position of the rectangular
    ;text box point before rotation. (before translation of the matrix)
    $iXt = ($iX - $x) * Cos($iAngle * $iPI / 180) + ($iY - $y) * Sin($iAngle * $iPI / 180)
    $iYt = -($iX - $x) * Sin($iAngle * $iPI / 180) + ($iY - $y) * Cos($iAngle * $iPI / 180)

    $hBrush = _GDIPlus_BrushCreateSolid($iARGB)
    $tLayout = _GDIPlus_RectFCreate($iXt, $iYt, $iWidth, $iHeight)
    _GDIPlus_GraphicsDrawStringEx($hGraphic, $nText, $hFont, $tLayout, $hFormat, $hBrush)

    ; Clean up resources
    _GDIPlus_MatrixDispose($hMatrix)
    _GDIPlus_FontDispose($hFont)
    _GDIPlus_FontFamilyDispose($hFamily)
    _GDIPlus_StringFormatDispose($hFormat)
    _GDIPlus_BrushDispose($hBrush)
    $tLayout = ""
    Return 1
EndFunc   ;==>GDIPlus_SetAngledText


Func Color_SetHSL($iHue, $Saturation = 180, $Brightness = 160)
    If IsArray($iHue) Then
        $aInput = $iHue
    Else
        Local $aInput[3] = [$iHue, $Saturation, $Brightness]
    EndIf
    Local $aiRGB = _ColorConvertHSLtoRGB($aInput)
    Return "0x" & Hex(Round($aiRGB[0]), 2) & Hex(Round($aiRGB[1]), 2) & Hex(Round($aiRGB[2]), 2)
EndFunc   ;==>Color_SetHSL


Func _AntiAlias($hGraphics)
    Local $aResult
    $aResult = DllCall($ghGDIPDll, "int", "GdipSetSmoothingMode", "hwnd", $hGraphics, "int", 2)
    If @error Then Return SetError(@error, @extended, False)
    Return SetError($aResult[0], 0, $aResult[0] = 0)
EndFunc   ;==>_AntiAlias


Func _Quit()
    If $hImage > 0 Then _GDIPlus_ImageDispose($hImage)
    _GDIPlus_Shutdown()
    Exit
EndFunc   ;==>_Quit
Edited by Malkey
Link to comment
Share on other sites

I had to see if this could be done.

....

That's great Malkey, it's a real captcha now. You should put it in example scripts or add it as an example in your angle text thread.

(I hadn't seen that angle text thread before, it's excellent. )

Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

Very good @Malkey, i agree with martin, now it's looks like a real captcha :)

Just one small (indeed) issue: When you minimize the GUI, the captcha control (Picture) is become smaller (shrinks), any idea why? :)

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

Very good @Malkey, i agree with martin, now it's looks like a real captcha :)

Just one small (indeed) issue: When you minimize the GUI, the captcha control (Picture) is become smaller (shrinks), any idea why? :)

Yes, it reverts to the creation size of the Graphic but I don't realy understand why. I suppose it's because resizing is applied to the original creation size. Same problem if you add a sizebox to the gui.

If you create it at a size 150 x 100 it's ok.

You can redraw it by registering $WM_PAINT

GuiRegisterMsg($WM_PAINT,"GuiPaint")
.
.
.
Func GuiPaint()
    controlmove("GDIPlus Graphics on Picture Control - OnEvent Mode","",$Pic,20,20,150,100) 
 ;Really needs 150,100 to be $iW, $iH and change those to Global instead of Local in the PicSetGraphics function.
EndFunc
Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

Just one small (indeed) issue: When you minimize the GUI, the captcha control (Picture) is become smaller (shrinks), any idea why? :)

Fixed it. Updated script.

Martin was right about reverting back to its creation size.

This was happening because of the DLLCall, SendMessage command which redraws after restore from minimumization.

Also, had to add a background label as the border. The send message was not recognizing the exstyles of the picture control or something.

Because with the border, the picture control size increases to 160 x 110. The DLLCall command returned the size back to 150 x100 with the border.

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...