Sign in to follow this  
Followers 0
mikeytown2

ImageMagick Batch jpg Processor

2 posts in this topic

#1 ·  Posted (edited)

Auto install ImageMagick if it's not there.

Auto rotate image baised on EXIF data.

Auto brightens dark areas

Auto resize shrinks to typical 3MP image

Recompresses jpg files to 70% quality for web use.

Dumps processed files in a dir on the desktop.

Grabed Code From my batch m2v maker

http://www.autoitscript.com/forum/index.php?showtopic=58691

and the ImageMagick Object

http://www.autoitscript.com/forum/index.php?showtopic=49065

#include <Array.au3>

; Basic ImageMagick Vars
Global $ret = 0
Global $info
Global $msgs
Global $elem
Global $sMsgs
Global Const $ERROR_SUCCESS = 0

ChkImageMagickInstall()

; ImageMagick Error handler
Global $oMyError = ObjEvent("AutoIt.Error", "MyErrFunc")
Global $img = ObjCreate("ImageMagickObject.MagickImage.1")

;Autoit Variables
Global $filelist[1]
$filelist[0] = 0
Global $filetype = "*.jpg"
Global $OutDir = @DesktopDir & "\" & @YEAR & "-" & @MON


ChkCmd()
ProcessImages()


; Install Imagemagick
Func ChkImageMagickInstall()
    If DirGetSize(@ProgramFilesDir & "\ImageMagick-6.4.7-Q16") == -1 Then
        ToolTip("Installing Image Processing Tools")
        FileInstall("ImageMagick-6.4.7-6-Q16-windows-dll.exe", "install.exe")
        RunWait("install.exe" & " /VERYSILENT" & ' /COMPONENTS="install_magick_dll"')
        ToolTip("Tools Installed")
        FileInstall("ImageMagickObject.dll", @ProgramFilesDir & "\ImageMagick-6.4.7-Q16\ImageMagickObject.dll")
        FileInstall("MagickCMD.exe", @ProgramFilesDir & "\MagickCMD.exe")
        Sleep(1000)
        RunWait(@ComSpec & " /c " & 'Regsvr32 /s "' & @ProgramFilesDir & '\ImageMagick-6.4.7-Q16\ImageMagickObject.dll"', "", @SW_HIDE)
        Sleep(1000)
        ToolTip("")
    EndIf
EndFunc

;Grab EXE Drag-n-Droped files/dir's
Func ChkCmd()
    ;Files where dropped onto exe
    If $CmdLine[0] > 0 Then
        ArrayToFileList($CmdLine)
    EndIf
EndFunc   ;==>ChkCmd

;add from given array to Filelist
Func ArrayToFileList($CmdLine)
    Local $dirbit = 0
    For $x = 1 To $CmdLine[0] Step +1 ;run though all files droped and look for dir's
        If StringInStr(FileGetAttrib($CmdLine[$x]), "D") Then
            $dirbit += 1
            FileListFromDir($CmdLine[$x]) ;parce dir looking for file of that extenstion
        Else ;add file to list
            _ArrayAdd($filelist, $CmdLine[$x])
            $filelist[0] += 1
        EndIf
    Next
EndFunc   ;==>ArrayToFileList

;add to array, list of files in a dir
Func FileListFromDir($dir)
    ;search for the first file with the correct file extenstion
    Local $file, $search = FileFindFirstFile($dir & "\" & $filetype)
    ; Check if the search was successful
    If $search = -1 Then
        MsgBox(0x40000, "Error", "No Picture " & $filetype & " files found")
    EndIf

    ;add found files to array
    While 1
        $file = FileFindNextFile($search)
        If @error Then
            ExitLoop
        EndIf
        ;Add file to array
        _ArrayAdd($filelist, $dir & "\" & $file)
        $filelist[0] += 1
    WEnd
    FileClose($search) ; Close the search handle
EndFunc   ;==>FileListFromDir


Func ProcessImages()
    ProgressOn("Image Processor", "Total of " & $filelist[0] & " images loaded for processing")
    DirCreate($OutDir)
    While DirGetSize($OutDir) == -1
        Sleep(250)
    WEnd
   
    Sleep(250)
    $step = 100 / $filelist[0]
    $increment = $step
    While $filelist[0] > 0
        Local $filein = $filelist[1]
        Local $fileout = ChangeOutputDir($filelist[1])
        ProgressSet($increment, Round($increment) & " percent")
        _ImageMagick_Quality($filein, "70", $fileout)
        If @error Then ExitLoop
        _ArrayDelete($filelist, 1)
        $filelist[0] -= 1
        $increment += $step
    WEnd
    ProgressSet(100 , "Done", "Complete")
    ShellExecute($OutDir)
    Sleep(500)
    ProgressOff()
EndFunc



; Error event
Func MyErrFunc()
  $HexNumber=hex($oMyError.number,8)
  Msgbox(0,"ImageMagick Error", "There was an ImageMagick error!"   & @CRLF  & @CRLF & _
             "err.description is: "                                 & @TAB & $oMyError.description   & @CRLF & _
             "err.windescription:"                  & @TAB & $oMyError.windescription & @CRLF & _
             "err.number is: "                    & @TAB & $HexNumber & @CRLF & _
             "err.lastdllerror is: "                                & @TAB & $oMyError.lastdllerror & @CRLF & _
             "err.scriptline is: "                  & @TAB & $oMyError.scriptline & @CRLF & _
             "err.source is: "                    & @TAB & $oMyError.source & @CRLF & _
             "err.helpfile is: "                                    & @TAB & $oMyError.helpfile & @CRLF & _
             "err.helpcontext is: "         & @TAB & $oMyError.helpcontext _
            )
  SetError(1) ; to check for after this function returns
EndFunc

Func _ImageMagick_Quality($sInFile, $sQuality, $sOutFile)
    $ret = $img.Convert($sInFile, _
        "-auto-orient", " ", _
        "-quality",$sQuality, _
        "-sigmoidal-contrast", "2,0%", _
        "-filter","Lagrange", _
        "-resize","2048x2048>", _
        $sOutFile)
    Return $ret
EndFunc

;change string to output dir right before it goes to HCenc.exe
Func ChangeOutputDir($fileout)
    Local $temp = StringSplit($fileout, "\")
    $fileout = $OutDir & "\" & $temp[$temp[0]]
    Return $fileout
EndFunc

Edit 12-12-2008:

Using -sigmoidal-contrast for image brightness

Added in Resize

Edited by mikeytown2

Share this post


Link to post
Share on other sites



Uses the latest (as of May 8th, 2011) version of ImageMagick. Has a slow mode (press no) which then uses this algorithm: smart sharpening in imagemagick

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=blue.ico
#AutoIt3Wrapper_Outfile=image.exe
#AutoIt3Wrapper_Compression=4
#AutoIt3Wrapper_Res_Language=1033
#AutoIt3Wrapper_Add_Constants=n
#AutoIt3Wrapper_Run_Tidy=y
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#cs ----------------------------------------------------------------------------
    
    AutoIt Version: 3.3.0.0
    Author:         myName
    
    Script Function:
    Template AutoIt script.
    
#ce ----------------------------------------------------------------------------

; Script Start - Add your code below here

#include <Array.au3>



; Basic ImageMagick Vars
Global $ret = 0
Global $info
Global $msgs
Global $elem
Global $sMsgs
Global Const $ERROR_SUCCESS = 0
; ImageMagick Error handler
ChkImageMagickInstall()
Global $oMyError = ObjEvent("AutoIt.Error", "MyErrFunc")
Global $img = ObjCreate("ImageMagickObject.MagickImage.1")

;Autoit Variables
Global $filelist[1]
$filelist[0] = 0
Global $filetype = "*.jpg"
Global $OutDir = @DesktopDir & "\" & @YEAR & "-" & @MON
Global $mode = 6

ChkCmd()
If $filelist[0] > 0 Then

    $mode = MsgBox(4, "Quality/Speed Selection", "Press Yes for speed, No for High quality mode (over 10 times slower).")


    ProcessImages()
Else
    MsgBox(0x40000, "Error", "No Picture " & $filetype & " files found")
EndIf

; Install Imagemagick
Func ChkImageMagickInstall()
    If DirGetSize(@ProgramFilesDir & "\ImageMagick-6.6.9-Q16") == -1 Then
        ToolTip("Installing Image Processing Tools")
        FileInstall("ImageMagick-6.6.9-8-Q16-windows-dll.exe", "install.exe")
        RunWait("install.exe" & " /VERYSILENT" & ' /COMPONENTS="install_magick_dll"')
        ToolTip("Tools Installed")
        Sleep(1000)
        FileInstall("ImageMagickObject.dll", @ProgramFilesDir & "\ImageMagick-6.6.9-Q16\ImageMagickObject.dll")
        FileInstall("MagickCMD.exe", @ProgramFilesDir & "\MagickCMD.exe")
        RunWait(@ComSpec & " /c " & 'Regsvr32 /s "' & @ProgramFilesDir & '\ImageMagick-6.6.9-Q16\ImageMagickObject.dll"', "", @SW_HIDE)
        Sleep(1000)
        ToolTip("")
    EndIf
EndFunc   ;==>ChkImageMagickInstall

;Grab EXE Drag-n-Droped files/dir's
Func ChkCmd()
    ;Files where dropped onto exe
    If $CmdLine[0] > 0 Then
        ArrayToFileList($CmdLine)
    Else
        $folder = FileSelectFolder("Choose The Folder That Contains All The Images.", "")
        If @error Then
            Return ''
        EndIf
        FileListFromDir($folder)
    EndIf
EndFunc   ;==>ChkCmd

;add from given array to Filelist
Func ArrayToFileList($CmdLine)
    Local $dirbit = 0
    For $x = 1 To $CmdLine[0] Step +1 ;run though all files droped and look for dir's
        If StringInStr(FileGetAttrib($CmdLine[$x]), "D") Then
            $dirbit += 1
            FileListFromDir($CmdLine[$x]) ;parce dir looking for file of that extenstion
        Else ;add file to list
            _ArrayAdd($filelist, $CmdLine[$x])
            $filelist[0] += 1
        EndIf
    Next
EndFunc   ;==>ArrayToFileList

;add to array, list of files in a dir
Func FileListFromDir($dir)
    ;search for the first file with the correct file extenstion
    Local $file, $search = FileFindFirstFile($dir & "\" & $filetype)
    ; Check if the search was successful
    If $search = -1 Then
        $searchDIR = FileFindFirstFile($dir & "\*")
        While 1
            $file = FileFindNextFile($searchDIR)
            If @error Then
                ExitLoop
            EndIf
            If StringInStr(FileGetAttrib($dir & "\" & $file), "D") Then
                FileListFromDir($dir & "\" & $file)
            EndIf
        WEnd
        FileClose($searchDIR) ; Close the search handle
    EndIf

    ;add found files to array
    While 1
        $file = FileFindNextFile($search)
        If @error Then
            ExitLoop
        EndIf
        ;Add file to array
        _ArrayAdd($filelist, $dir & "\" & $file)
        $filelist[0] += 1
    WEnd
    FileClose($search) ; Close the search handle
EndFunc   ;==>FileListFromDir

Func ProcessImages()
    ProgressOn("Image Processor", "Total of " & $filelist[0] & " images loaded for processing", "", "", "", 16)
    DirCreate($OutDir)
    While DirGetSize($OutDir) == -1
        Sleep(250)
    WEnd

    Sleep(250)
    $step = 100 / $filelist[0]
    $increment = $step
    $counter = 0
    While $filelist[0] > 0
        Local $filein = $filelist[1]
        Local $fileout = ChangeOutputDir($filelist[1])
        ProgressSet($increment, Round($increment) & " percent. " & $counter & " files done.")
        If $mode == 6 Then
            $out = _ImageMagick_Quality($filein, "70", $fileout)
        Else
            $out = _ImageMagick_Sharpen($filein, $fileout)
        EndIf
        ConsoleWrite($out)
        If @error Then ExitLoop
        _ArrayDelete($filelist, 1)
        $filelist[0] -= 1
        $increment += $step
        $counter += 1
    WEnd
    ProgressSet(100, "Done", "Complete")
    ShellExecute($OutDir)
    Sleep(500)
    ProgressOff()
EndFunc   ;==>ProcessImages



; Error event
Func MyErrFunc()
    $HexNumber = Hex($oMyError.number, 8)
    MsgBox(0, "ImageMagick Error", "There was an ImageMagick error!" & @CRLF & @CRLF & _
            "err.description is: " & @TAB & $oMyError.description & @CRLF & _
            "err.windescription:" & @TAB & $oMyError.windescription & @CRLF & _
            "err.number is: " & @TAB & $HexNumber & @CRLF & _
            "err.lastdllerror is: " & @TAB & $oMyError.lastdllerror & @CRLF & _
            "err.scriptline is: " & @TAB & $oMyError.scriptline & @CRLF & _
            "err.source is: " & @TAB & $oMyError.source & @CRLF & _
            "err.helpfile is: " & @TAB & $oMyError.helpfile & @CRLF & _
            "err.helpcontext is: " & @TAB & $oMyError.helpcontext _
            )
    SetError(1) ; to check for after this function returns
EndFunc   ;==>MyErrFunc

Func _ImageMagick_Sharpen($sInFile, $sOutFile)
    $sharp_radius = 5
    $sharp_sigma = Sqrt($sharp_radius)
    $sharp_amount = 1.2
    $sharp_threshold = 0.003
    $a1 = 0
    $b1 = 0
    $c1 = 1.2
    $d1 = -0.1
    $blur_radius = 3
    $blur_sigma = Sqrt($blur_radius)
    $edge_width = 2
    $clip_low = "40" ;percentage left totally untouched by the sharpening
    $clip_high = "1" ;percentage sharpened full strength

    $img.Convert($sInFile, _
            "-auto-orient", _
            "-resize", "3145732@\>", _
            "-quality", "00", _
            $sOutFile & ".png")

    ;first make the edges
    $img.Convert($sOutFile & ".png", _
            "-edge", $edge_width, " ", _
            "-colorspace", "Gray ", _
            "-quality", "00", _
            $sOutFile & "_inner_edges.png")
    $img.Convert($sOutFile & ".png", _
            "-negate", " ", _
            "-edge", $edge_width, " ", _
            "-colorspace", "Gray ", _
            "-quality", "00", _
            $sOutFile & "_outer_edges.png")
    $img.Composite("-compose", "plus", _
            $sOutFile & "_inner_edges.png", _
            $sOutFile & "_outer_edges.png", _
            "-quality", "00", _
            $sOutFile & "_added_edges.png")
    $img.Convert($sOutFile & "_added_edges.png", _
            "-gaussian-blur", $blur_radius & "x" & $blur_sigma, _
            "-quality", "00", _
            $sOutFile & "_edges_blurred.png")
    $ret = $img.Convert($sOutFile & "_edges_blurred.png", _
            "-linear-stretch", $clip_low & "%x" & $clip_high, _
            "-quality", "00", _
            $sOutFile & "_edges.png")

    ;then get the value channel and sharpen it
    $img.Convert($sOutFile & ".png", _
            "-colorspace", "HSB", " ", _
            "-channel", "B", " ", _
            "-separate", " ", _
            "-quality", "00", _
            $sOutFile & "_value.png")
    $img.Convert($sOutFile & "_value.png", _
            "-unsharp", $sharp_radius & "x" & $sharp_sigma & "+" & $sharp_amount & "+" & $sharp_threshold, " ", _
            "-quality", "00", _
            $sOutFile & "_value_8.png")
    $img.Composite($sOutFile & "_value_8.png", _
            $sOutFile & "_value.png", _
            $sOutFile & "_edges.png", _
            "-quality", "00", _
            $sOutFile & "_value_partial_sharp.png")

    ;then get the hue and saturation channels
    $img.Convert($sOutFile & ".png", _
            "-colorspace", "HSB", " ", _
            "-channel", "R", " ", _
            "-separate", " ", _
            "-quality", "00", _
            $sOutFile & "_hue.png")
    $img.Convert($sOutFile & ".png", _
            "-colorspace", "HSB", " ", _
            "-channel", "G", " ", _
            "-separate", " ", _
            "-quality", "00", _
            $sOutFile & "_saturation.png")

    FileDelete($sOutFile & "_inner_edges.png")
    FileDelete($sOutFile & "_outer_edges.png")
    FileDelete($sOutFile & "_added_edges.png")
    FileDelete($sOutFile & "_edges_blurred.png")
    FileDelete($sOutFile & "_edges.png")
    FileDelete($sOutFile & "_value.png")
    FileDelete($sOutFile & "_value_8.png")
    FileDelete($sOutFile & ".png")

    ;finally put it all together
    $img.Convert($sOutFile & "_hue.png", "-colorspace", "HSB", _
            $sOutFile & "_hue.png", "-compose", "CopyRed", "-composite", _
            $sOutFile & "_saturation.png", "-compose", "CopyGreen", "-composite", _
            $sOutFile & "_value_partial_sharp.png", "-compose", "CopyBlue", "-composite", _
            "-colorspace", "RGB", _
            "-quality", "00", _
            $sOutFile & "_smartsharp.png")

    ;auto level
    $ret = $img.Convert($sOutFile & "_smartsharp.png", _
            "-auto-level", _
            "-quality", "00", _
            $sOutFile & ".png")

    ;compress to jpeg
    $ret = $img.Convert($sOutFile & ".png", _
            "-quality", "70", _
            "-contrast-stretch", "1.5%x2%", _
            $sOutFile)

    FileDelete($sOutFile & ".png")
    FileDelete($sOutFile & "_hue.png")
    FileDelete($sOutFile & "_saturation.png")
    FileDelete($sOutFile & "_value_partial_sharp.png")
    FileDelete($sOutFile & "_smartsharp.png")

    Return $ret
EndFunc   ;==>_ImageMagick_Sharpen

Func _ImageMagick_Quality($sInFile, $sQuality, $sOutFile)
    $ret = $img.Convert($sInFile, _
            "-auto-level", _
            "-auto-orient", " ", _
            "-contrast-stretch", "1.5%x2%", _
            "-resize", "3145732@\>", _
            "-quality", $sQuality, _
            $sOutFile)
    Return $ret
EndFunc   ;==>_ImageMagick_Quality

;change string to output dir right before it goes to HCenc.exe
Func ChangeOutputDir($fileout)
    Local $temp = StringSplit($fileout, "\")
    $fileout = $OutDir & "\" & $temp[$temp[0]]
    Return $fileout
EndFunc   ;==>ChangeOutputDir

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
Sign in to follow this  
Followers 0