-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageOptimizer.ps1
More file actions
188 lines (171 loc) · 24.3 KB
/
ImageOptimizer.ps1
File metadata and controls
188 lines (171 loc) · 24.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# Ultimate Image Optimizer Pro (WPF Edition)
# MIT License | Copyright (c) 2026 Bishnu Mahali
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# ==========================================
# THEME ENGINE
# ==========================================
function Get-SystemTheme {
try {
$reg = Get-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize" -ErrorAction SilentlyContinue
if ($reg.AppsUseLightTheme -eq 0) { return "Dark" }
} catch {}
return "Light"
}
$CurrentTheme = Get-SystemTheme
$Theme = if ($CurrentTheme -eq "Dark") {
@{ WindowBg="#1B1F23"; CardBg="#24292E"; TextMain="#E6EDF3"; TextSub="#8C959F"; Border="#30363D"; InputBg="#0D1117"; Primary="#007BFF"; Accent="#0969DA"; Shadow="#000000"; ProgressBg="#30363D"; Hover="#1F883D"; Success="#28A745"; Error="#E74C3C" }
} else {
@{ WindowBg="#F8F9FA"; CardBg="#FFFFFF"; TextMain="#1A1A1A"; TextSub="#6C757D"; Border="#DEE2E6"; InputBg="#F8F9FA"; Primary="#007BFF"; Accent="#007BFF"; Shadow="#E0E0E0"; ProgressBg="#E9ECEF"; Hover="#0056B3"; Success="#28A745"; Error="#E74C3C" }
}
# ==========================================
# XAML UI DEFINITION
# ==========================================
[xml]$xaml = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Image Optimizer Pro" Height="850" Width="1100" Background="$($Theme.WindowBg)" WindowStartupLocation="CenterScreen">
<Window.Resources>
<ControlTemplate x:Key="ComboBoxTemplate" TargetType="ComboBox">
<Grid>
<ToggleButton Name="ToggleButton" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" IsChecked="{Binding Path=IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" ClickMode="Press">
<ToggleButton.Template>
<ControlTemplate TargetType="ToggleButton">
<Border Name="Border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4">
<Grid HorizontalAlignment="Right" Width="24"><Path Name="Arrow" Fill="{TemplateBinding Foreground}" Data="M 0 0 L 4 4 L 8 0 Z" VerticalAlignment="Center" HorizontalAlignment="Center"/></Grid>
</Border>
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
<ContentPresenter Name="ContentSite" IsHitTestVisible="False" Content="{TemplateBinding SelectionBoxItem}" ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" Margin="10,3,30,3" VerticalAlignment="Center" HorizontalAlignment="Left" />
<Popup Name="Popup" Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}" AllowsTransparency="True" Focusable="False" PopupAnimation="Slide">
<Grid Name="DropDown" SnapsToDevicePixels="True" MinWidth="{TemplateBinding ActualWidth}" MaxHeight="{TemplateBinding MaxDropDownHeight}"><Border Name="DropDownBorder" Background="$($Theme.InputBg)" BorderBrush="$($Theme.Border)" BorderThickness="1" CornerRadius="4"><ScrollViewer Margin="0" SnapsToDevicePixels="True"><StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" /></ScrollViewer></Border></Grid>
</Popup>
</Grid>
</ControlTemplate>
<ControlTemplate x:Key="CheckBoxTemplate" TargetType="CheckBox">
<StackPanel Orientation="Horizontal">
<Border Width="16" Height="16" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1" Background="{TemplateBinding Background}" CornerRadius="2"><Path Name="CheckMark" Fill="{TemplateBinding Foreground}" Data="M 0 5 L 4 9 L 10 0" Visibility="Collapsed" Stroke="{TemplateBinding Foreground}" StrokeThickness="2" Margin="2" /></Border>
<ContentPresenter Margin="8,0,0,0" VerticalAlignment="Center" />
</StackPanel>
<ControlTemplate.Triggers><Trigger Property="IsChecked" Value="True"><Setter TargetName="CheckMark" Property="Visibility" Value="Visible" /></Trigger></ControlTemplate.Triggers>
</ControlTemplate>
<Style TargetType="TextBlock"><Setter Property="Foreground" Value="$($Theme.TextMain)"/></Style>
<Style TargetType="CheckBox"><Setter Property="Template" Value="{StaticResource CheckBoxTemplate}"/><Setter Property="Foreground" Value="$($Theme.TextMain)"/></Style>
<Style TargetType="RadioButton"><Setter Property="Foreground" Value="$($Theme.TextMain)"/></Style>
<Style TargetType="TextBox"><Setter Property="Background" Value="$($Theme.InputBg)"/><Setter Property="Foreground" Value="$($Theme.TextMain)"/><Setter Property="BorderBrush" Value="$($Theme.Border)"/><Setter Property="VerticalContentAlignment" Value="Center"/><Setter Property="Padding" Value="5"/></Style>
<Style TargetType="ComboBox"><Setter Property="Template" Value="{StaticResource ComboBoxTemplate}" /><Setter Property="Background" Value="$($Theme.InputBg)"/><Setter Property="Foreground" Value="$($Theme.TextMain)"/><Setter Property="BorderBrush" Value="$($Theme.Border)"/><Setter Property="Height" Value="32"/></Style>
<Style TargetType="ComboBoxItem"><Setter Property="Background" Value="Transparent"/><Setter Property="Foreground" Value="$($Theme.TextMain)"/><Setter Property="Padding" Value="10,6"/><Style.Triggers><Trigger Property="IsHighlighted" Value="True"><Setter Property="Background" Value="$($Theme.Accent)"/><Setter Property="Foreground" Value="White"/></Trigger></Style.Triggers></Style>
<Style TargetType="DataGrid"><Setter Property="Background" Value="$($Theme.InputBg)"/><Setter Property="BorderBrush" Value="$($Theme.Border)"/><Setter Property="Foreground" Value="$($Theme.TextMain)"/><Setter Property="RowBackground" Value="$($Theme.CardBg)"/><Setter Property="AlternatingRowBackground" Value="$($Theme.InputBg)"/><Setter Property="HorizontalGridLinesBrush" Value="$($Theme.Border)"/><Setter Property="VerticalGridLinesBrush" Value="$($Theme.Border)"/><Setter Property="BorderThickness" Value="1"/><Setter Property="FontSize" Value="13"/><Setter Property="RowHeight" Value="32"/><Setter Property="VirtualizingPanel.IsVirtualizing" Value="True"/><Setter Property="VirtualizingPanel.VirtualizationMode" Value="Recycling"/></Style>
<Style TargetType="DataGridColumnHeader"><Setter Property="Background" Value="$($Theme.InputBg)"/><Setter Property="Foreground" Value="$($Theme.TextSub)"/><Setter Property="Padding" Value="10,8"/><Setter Property="FontWeight" Value="Bold"/><Setter Property="BorderBrush" Value="$($Theme.Border)"/><Setter Property="BorderThickness" Value="0,0,1,1"/></Style>
<Style TargetType="DataGridCell"><Setter Property="BorderThickness" Value="0"/><Setter Property="Padding" Value="10,5"/><Style.Triggers><Trigger Property="IsSelected" Value="True"><Setter Property="Background" Value="$($Theme.Accent)"/><Setter Property="Foreground" Value="White"/></Trigger></Style.Triggers></Style>
<Style x:Key="CardStyle" TargetType="Border"><Setter Property="Background" Value="$($Theme.CardBg)"/><Setter Property="CornerRadius" Value="12"/><Setter Property="Padding" Value="20"/><Setter Property="Margin" Value="0,0,0,20"/><Setter Property="BorderBrush" Value="$($Theme.Border)"/><Setter Property="BorderThickness" Value="1"/><Setter Property="Effect"><Setter.Value><DropShadowEffect BlurRadius="15" Color="$($Theme.Shadow)" ShadowDepth="2" Opacity="0.3"/></Setter.Value></Setter></Style>
<Style x:Key="PrimaryButtonStyle" TargetType="Button"><Setter Property="Background" Value="$($Theme.Primary)"/><Setter Property="Foreground" Value="White"/><Setter Property="FontWeight" Value="Bold"/><Setter Property="Padding" Value="25,12"/><Setter Property="BorderThickness" Value="0"/><Setter Property="Cursor" Value="Hand"/><Setter Property="Height" Value="45"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Button"><Border Name="Border" Background="{TemplateBinding Background}" CornerRadius="6"><ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/></Border><ControlTemplate.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter TargetName="Border" Property="Background" Value="$($Theme.Hover)"/></Trigger><Trigger Property="IsEnabled" Value="False"><Setter Name="Border" Background="$($Theme.ProgressBg)" Foreground="$($Theme.TextSub)"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style>
<Style x:Key="SecondaryButtonStyle" TargetType="Button"><Setter Property="Background" Value="$($Theme.InputBg)"/><Setter Property="Foreground" Value="$($Theme.TextMain)"/><Setter Property="BorderBrush" Value="$($Theme.Border)"/><Setter Property="BorderThickness" Value="1"/><Setter Property="Cursor" Value="Hand"/><Setter Property="Height" Value="35"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Button"><Border Name="Border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4"><ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/></Border><ControlTemplate.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter TargetName="Border" Property="Background" Value="$($Theme.CardBg)"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style>
</Window.Resources>
<Grid Margin="30">
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
<StackPanel Grid.Row="0" Margin="0,0,0,25"><TextBlock Text="IMAGE OPTIMIZER PRO" FontWeight="ExtraBold" FontSize="26"/><TextBlock Text="Fast, professional image compression and format conversion" Foreground="$($Theme.TextSub)" FontSize="14"/></StackPanel>
<Grid Grid.Row="1"><Grid.ColumnDefinitions><ColumnDefinition Width="400"/><ColumnDefinition Width="*"/></Grid.ColumnDefinitions>
<ScrollViewer Grid.Column="0" VerticalScrollBarVisibility="Auto" Margin="0,0,20,0"><StackPanel>
<Border Style="{StaticResource CardStyle}"><StackPanel><TextBlock Text="1. TARGET FOLDER" FontWeight="Bold" Margin="0,0,0,8" Foreground="$($Theme.TextSub)"/><Grid><Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions><TextBox x:Name="txtPath" IsReadOnly="True"/><Button x:Name="btnBrowse" Grid.Column="1" Content="Browse" Width="80" Margin="8,0,0,0" Style="{StaticResource SecondaryButtonStyle}"/></Grid><CheckBox x:Name="chkRecursive" Content="Include Subfolders" Margin="0,12,0,0"/></StackPanel></Border>
<Border Style="{StaticResource CardStyle}"><StackPanel><TextBlock Text="2. OPTIMIZATION" FontWeight="Bold" Margin="0,0,0,15" Foreground="$($Theme.TextSub)"/><ComboBox x:Name="comboFormat" Height="32" Margin="0,0,0,15"><ComboBoxItem Content="Original Format" IsSelected="True"/><ComboBoxItem Content="WebP (Modern)"/><ComboBoxItem Content="JPEG (Universal)"/><ComboBoxItem Content="PNG (Lossless)"/></ComboBox><Grid><TextBlock Text="Quality"/><TextBlock x:Name="lblQualityVal" Text="80%" HorizontalAlignment="Right" FontWeight="Bold" Foreground="$($Theme.Accent)"/></Grid><Slider x:Name="sliderQuality" Minimum="10" Maximum="100" Value="80" TickFrequency="5" IsSnapToTickEnabled="True" Margin="0,5,0,15"/><ComboBox x:Name="comboResize" Height="32"><ComboBoxItem Content="No Resizing" IsSelected="True"/><ComboBoxItem Content="4K (3840px)"/><ComboBoxItem Content="2K (2048px)"/><ComboBoxItem Content="Full HD (1920px)"/><ComboBoxItem Content="HD (1280px)"/></ComboBox></StackPanel></Border>
<Border Style="{StaticResource CardStyle}"><StackPanel><TextBlock Text="3. OPTIONS" FontWeight="Bold" Margin="0,0,0,15" Foreground="$($Theme.TextSub)"/><RadioButton x:Name="rbCopy" Content="Save as Copy (_opt)" IsChecked="True" Margin="0,0,0,10"/><RadioButton x:Name="rbOverwrite" Content="Overwrite Original" Margin="0,0,0,10"/><CheckBox x:Name="chkStrip" Content="Strip Metadata" IsChecked="True"/></StackPanel></Border>
<Border Style="{StaticResource CardStyle}"><StackPanel><TextBlock Text="4. SESSION OPTIONS" FontWeight="Bold" Foreground="$($Theme.TextSub)" Margin="0,0,0,10"/><CheckBox x:Name="chkResume" Content="Enable Resume Functionality" IsChecked="True" Margin="0,0,0,8"/><CheckBox x:Name="chkCache" Content="Enable Cache for Faster Processing" IsChecked="True" Margin="0,0,0,8"/><CheckBox x:Name="chkLog" Content="Enable Log" IsChecked="True"/></StackPanel></Border>
</StackPanel></ScrollViewer>
<Grid Grid.Column="1"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
<UniformGrid Grid.Row="0" Columns="3" Margin="0,0,0,20">
<Border Style="{StaticResource CardStyle}" Margin="0,0,10,0" Padding="15"><StackPanel HorizontalAlignment="Center"><TextBlock Text="FOUND" FontSize="10" Foreground="$($Theme.TextSub)" FontWeight="Bold"/><TextBlock x:Name="statFound" Text="0" FontSize="22" FontWeight="Bold"/></StackPanel></Border>
<Border Style="{StaticResource CardStyle}" Margin="5,0,5,0" Padding="15"><StackPanel HorizontalAlignment="Center"><TextBlock Text="SAVED" FontSize="10" Foreground="$($Theme.Success)" FontWeight="Bold"/><TextBlock x:Name="statSaved" Text="0 MB" FontSize="22" FontWeight="Bold"/></StackPanel></Border>
<Border Style="{StaticResource CardStyle}" Margin="10,0,0,0" Padding="15"><StackPanel HorizontalAlignment="Center"><TextBlock Text="EFFICIENCY" FontSize="10" Foreground="$($Theme.Accent)" FontWeight="Bold"/><TextBlock x:Name="statPct" Text="0%" FontSize="22" FontWeight="Bold"/></StackPanel></Border>
</UniformGrid>
<Border Grid.Row="1" Style="{StaticResource CardStyle}" Padding="0"><DataGrid x:Name="dgFiles" AutoGenerateColumns="False" IsReadOnly="True" BorderThickness="0" Background="Transparent" GridLinesVisibility="Horizontal" HeadersVisibility="Column"><DataGrid.Columns><DataGridTextColumn Header="Filename" Binding="{Binding Name}" Width="*"/><DataGridTextColumn Header="Old" Binding="{Binding OldSize}" Width="80"/><DataGridTextColumn Header="New" Binding="{Binding NewSize}" Width="80"/><DataGridTextColumn Header="Saving" Binding="{Binding Saving}" Width="70"><DataGridTextColumn.ElementStyle><Style TargetType="TextBlock"><Setter Property="Foreground" Value="$($Theme.Success)"/><Setter Property="FontWeight" Value="Bold"/></Style></DataGridTextColumn.ElementStyle></DataGridTextColumn><DataGridTextColumn Header="Status" Binding="{Binding Status}" Width="100"/></DataGrid.Columns></DataGrid></Border>
<StackPanel Grid.Row="2" Margin="0,15,0,0"><Grid Margin="0,0,0,8"><TextBlock x:Name="lblProgress" Text="Ready"/><TextBlock x:Name="lblPctProgress" Text="0%" HorizontalAlignment="Right" FontWeight="Bold" Foreground="$($Theme.Accent)"/></Grid><ProgressBar x:Name="progressMain" Height="8" Minimum="0" Maximum="100" Value="0" Background="$($Theme.ProgressBg)" Foreground="$($Theme.Accent)" BorderThickness="0"/></StackPanel>
</Grid>
</Grid>
<Grid Grid.Row="2" Margin="0,20,0,0"><StackPanel Orientation="Horizontal" VerticalAlignment="Center"><TextBlock Text="Engine: "/><TextBlock x:Name="lblEngineStatus" Text="..." FontWeight="Bold"/></StackPanel><Button x:Name="btnStart" Content="START OPTIMIZATION" Style="{StaticResource PrimaryButtonStyle}" HorizontalAlignment="Right" Width="220"/></Grid>
</Grid>
</Window>
"@
# Logic
$reader = New-Object System.Xml.XmlNodeReader $xaml; $window = [Windows.Markup.XamlReader]::Load($reader)
$txtPath = $window.FindName("txtPath"); $btnBrowse = $window.FindName("btnBrowse"); $chkRecursive = $window.FindName("chkRecursive")
$comboFormat = $window.FindName("comboFormat"); $lblQualityVal = $window.FindName("lblQualityVal"); $sliderQuality = $window.FindName("sliderQuality")
$comboResize = $window.FindName("comboResize"); $rbCopy = $window.FindName("rbCopy"); $rbOverwrite = $window.FindName("rbOverwrite"); $chkStrip = $window.FindName("chkStrip")
$chkResume = $window.FindName("chkResume"); $chkCache = $window.FindName("chkCache"); $chkLog = $window.FindName("chkLog")
$statFound = $window.FindName("statFound"); $statSaved = $window.FindName("statSaved"); $statPct = $window.FindName("statPct"); $dgFiles = $window.FindName("dgFiles")
$lblProgress = $window.FindName("lblProgress"); $lblPctProgress = $window.FindName("lblPctProgress"); $progressMain = $window.FindName("progressMain")
$lblEngineStatus = $window.FindName("lblEngineStatus"); $btnStart = $window.FindName("btnStart")
$global:imgFiles = @(); $imgExts = @(".jpg", ".jpeg", ".png", ".webp", ".avif", ".bmp", ".tiff")
$global:logEnabled = $false; $global:logFilePath = ""
function Add-Log {
param([string]$msg)
$window.Dispatcher.Invoke({
$ts = "$(Get-Date -Format 'HH:mm:ss') - $msg"
$lblProgress.Text = $msg
if ($global:logEnabled -and $global:logFilePath) { try { Add-Content -Path $global:logFilePath -Value $ts -ErrorAction SilentlyContinue } catch {} }
})
}
function Format-Bytes { param([long]$Bytes) if ($Bytes -ge 1GB) { return "$([math]::Round($Bytes / 1GB, 2)) GB" }; if ($Bytes -ge 1MB) { return "$([math]::Round($Bytes / 1MB, 2)) MB" }; if ($Bytes -ge 1KB) { return "$([math]::Round($Bytes / 1KB, 2)) KB" }; return "$Bytes B" }
function Check-Engine { if (Get-Command magick -ErrorAction SilentlyContinue) { $lblEngineStatus.Text = "ImageMagick"; $lblEngineStatus.Foreground = [System.Windows.Media.Brushes]::Green; return "magick" }; $lblEngineStatus.Text = "Native"; $lblEngineStatus.Foreground = [System.Windows.Media.Brushes]::Gray; return "native" }
function Scan-Files {
$path = $txtPath.Text; if ([string]::IsNullOrWhiteSpace($path) -or -not (Test-Path -LiteralPath $path)) { return }
$files = Get-ChildItem -LiteralPath $path -File -Recurse:$chkRecursive.IsChecked | Where-Object { $imgExts -contains $_.Extension.ToLower() }
$global:imgFiles = $files | ForEach-Object { [PSCustomObject]@{ Name=$_.Name; FullName=$_.FullName; Directory=$_.DirectoryName; Extension=$_.Extension; OldSize=(Format-Bytes $_.Length); OldSizeBytes=$_.Length; NewSize="---"; Saving="---"; Status="Queued" } }
$dgFiles.ItemsSource = [System.Collections.ObjectModel.ObservableCollection[PSCustomObject]]$global:imgFiles; $statFound.Text = $global:imgFiles.Count
}
$txtPath.Text = $PWD.Path; Check-Engine; Scan-Files
$btnBrowse.Add_Click({ Add-Type -AssemblyName System.Windows.Forms; $dialog = New-Object System.Windows.Forms.FolderBrowserDialog; $dialog.SelectedPath = $txtPath.Text; if ($dialog.ShowDialog() -eq "OK") { $txtPath.Text = $dialog.SelectedPath; Scan-Files } })
$sliderQuality.Add_ValueChanged({ $lblQualityVal.Text = "$([int]$sliderQuality.Value)%" })
$chkResume.Add_Click({ if ($chkResume.IsChecked) { $chkCache.IsChecked = $true } }); $chkCache.Add_Click({ if (-not $chkCache.IsChecked) { $chkResume.IsChecked = $false } })
$btnStart.Add_Click({
if ($global:imgFiles.Count -eq 0) { return }; $btnStart.IsEnabled=$false; $btnBrowse.IsEnabled=$false; $engine = Check-Engine
$global:logEnabled = $chkLog.IsChecked
$workDir = Join-Path $txtPath.Text ".Image Optimizer"
if ($chkCache.IsChecked -or $chkLog.IsChecked) { if (-not (Test-Path $workDir)) { $hd = New-Item -ItemType Directory -Path $workDir -Force; $hd.Attributes = "Directory", "Hidden" } }
$cacheFile = Join-Path $workDir "Cache.json"; $global:logFilePath = Join-Path $workDir "Log.txt"
$cache = @{}; if ($chkResume.IsChecked -and (Test-Path $cacheFile)) { try { $json = Get-Content $cacheFile -Raw | ConvertFrom-Json; foreach ($e in $json) { if ($e.Path) { $cache[$e.Path.ToLowerInvariant()] = $e } } } catch {} }
$config = @{ Quality = [int]$sliderQuality.Value; Format = switch($comboFormat.SelectedIndex){ 1{"webp"}; 2{"jpg"}; 3{"png"}; default{""} }; Resize = switch($comboResize.SelectedIndex){ 1{3840}; 2{2048}; 3{1920}; 4{1280}; default{0} }; Strip = $chkStrip.IsChecked; Mode = if($rbOverwrite.IsChecked){"Overwrite"} else{"Copy"}; CacheEnabled=$chkCache.IsChecked; CacheFile=$cacheFile; Cache=$cache; ResumeEnabled=$chkResume.IsChecked }
$global:processedCount = 0; $global:totalSavedBytes = 0; $global:totalOriginalBytes = 0
$job = { param($files, $config, $engine)
foreach ($f in $files) {
$key = $f.FullName.ToLowerInvariant();
$realFile = Get-Item -LiteralPath "$($f.FullName)"
$sig = "$($f.OldSizeBytes)|$($realFile.LastWriteTimeUtc.Ticks)"
if ($config.ResumeEnabled -and $config.Cache.ContainsKey($key)) {
if ($config.Cache[$key].Signature -eq $sig) { Write-Output @{ Index=[array]::IndexOf($files, $f); Success=$false; Msg="Cached Skip"; Total=$files.Count; File=$f.Name }; continue }
}
$res = @{ Success=$false; NewSize=0; Msg="Failed" }; $ext = if($config.Format){ ".$($config.Format)" } else { $f.Extension }; $out = Join-Path $f.Directory ($f.Name.Replace($f.Extension, "") + "_opt" + $ext)
try {
if ($engine -eq "magick") {
$magickArgs = @($f.FullName, "-quality", $config.Quality); if($config.Strip){ $magickArgs += "-strip" }; if($config.Resize -gt 0){ $magickArgs += @("-resize", "$($config.Resize)x$($config.Resize)>") }; $magickArgs += $out; Start-Process magick -ArgumentList $magickArgs -NoNewWindow -Wait; if($LASTEXITCODE -eq 0){ $res.Success=$true }
} else {
$img = [System.Drawing.Image]::FromFile($f.FullName);
$targetFormat = [System.Drawing.Imaging.ImageFormat]::Jpeg
if($config.Format -eq "png"){ $targetFormat = [System.Drawing.Imaging.ImageFormat]::Png }
$img.Save($out, $targetFormat); $img.Dispose(); $res.Success = $true
}
if ($res.Success -and (Test-Path $out)) { $newSize = (Get-Item $out).Length; if ($newSize -lt $f.OldSizeBytes) { if ($config.Mode -eq "Overwrite") { Remove-Item $f.FullName -Force; Move-Item $out $f.FullName -Force }; $res.NewSize = $newSize } else { Remove-Item $out -Force; $res.Msg = "Size Increase" } }
} catch { $res.Msg = "Error" }
if ($config.CacheEnabled) { $config.Cache[$key] = @{ Path=$f.FullName; Signature=$sig; Status=$res.Msg }; $config.Cache.Values | ConvertTo-Json -Depth 4 | Set-Content $config.CacheFile }
Write-Output @{ Index=[array]::IndexOf($files, $f); Success=$res.Success; NewSize=$res.NewSize; Msg=$res.Msg; Total=$files.Count; File=$f.Name }
}
}
$powershell = [PowerShell]::Create().AddScript($job).AddArgument($global:imgFiles).AddArgument($config).AddArgument($engine); $asyncResult = $powershell.BeginInvoke()
$timer = New-Object System.Windows.Threading.DispatcherTimer; $timer.Interval = [TimeSpan]::FromMilliseconds(100)
$timer.Add_Tick({
if ($asyncResult.IsCompleted) { $timer.Stop(); $btnStart.IsEnabled=$true; $btnBrowse.IsEnabled=$true; Add-Log "Optimization Complete"; return }
if ($null -ne $powershell -and $null -ne $powershell.Streams.Output) {
$outputs = $powershell.Streams.Output | Select-Object -Last 10; $powershell.Streams.Output.Clear()
foreach ($out in $outputs) {
$item = $global:imgFiles[$out.Index]
if ($out.Success) { $item.Status = "Done"; $item.NewSize = Format-Bytes $out.NewSize; $saving = $item.OldSizeBytes - $out.NewSize; $item.Saving = "$([Math]::Round(($saving / $item.OldSizeBytes) * 100, 1))%"; $global:totalSavedBytes += $saving; $global:totalOriginalBytes += $item.OldSizeBytes } else { $item.Status = $out.Msg; $item.Saving = "0%" }
$global:processedCount++; $statSaved.Text = Format-Bytes $global:totalSavedBytes; if ($global:totalOriginalBytes -gt 0) { $statPct.Text = "$([Math]::Round(($global:totalSavedBytes / $global:totalOriginalBytes) * 100, 1))%" }; $pctTotal = [Math]::Round(($global:processedCount / $out.Total) * 100); $progressMain.Value = $pctTotal; $lblPctProgress.Text = "$pctTotal%"; Add-Log "Processing: $($out.File)"
}
}
$dgFiles.Items.Refresh()
})
$timer.Start()
})
$window.ShowDialog() | Out-Null