TEST

[ChatGPT opens mouth to write program] Full record: GIF animation size scaling (with Magick)

Now you can write programs without being an architect or supervisor
But you still need to know some terminology, otherwise you may spend a lot of communication costs with AI.
I talked for about an hour before and after, and some people may complain about it, so it’s better to write it myself www
But it's cool to open your mouth The result is not to type

to program novice

What is this? This is a software that helps you change the size of GIF animations~It is very suitable for Discord's Emoji or Source game pre-painting.

Compared with catching unknown software on the Internet, this program is 100 times safer, and you don't have to worry about being poisoned! (Unless you don't trust ImageMagick)

People who just want an animated Gif resizer that works on Windows, just do this:

  1. Download and install https://imagemagick.org/archive/binaries/ImageMagick-7.1.1-7-Q16-HDRI-x64-dll.exe
  2. Check Add to system path
  3. Open Notepad, copy the complete code, and save it as gif_resizer.ps1
  4. right gif_resizer.ps1 Click the right mouse button, click Execute with Powershell
  5. start using!

Those who have problems, do not need to register or log in to the account, just leave a message below.

full code

Add-Type -AssemblyName System.Windows.Forms Add-Type -TypeDefinition @" using System; using System.Windows.Forms; public class FileDropLabel : Label { public FileDropLabel() { AllowDrop = true; DragEnter += (s, e) => { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; }; } } "@ -ReferencedAssemblies @('System.Windows.Forms.dll', 'System.Drawing.dll ') $global:originalWidth = [ref]0 $global:originalHeight = [ref]0 $global:inputImagePath = New-Object System.Management.Automation.PSReference("") function UpdateAspectRatio { if ($checkboxMaintainAspectRatio.Checked -and $checkboxMaintainAspectRatio.Checked -and $ Value -gt 0 -and $global:originalHeight.Value -gt 0) { if ($textboxWidth.Focused) { if ([int32]::TryParse($textboxWidth.Text, [ref]$null)) { $height = [int]($textboxWidth .Text) * $global:originalHeight.Value / $global:originalWidth.Value $textboxHeight.Text = [string]$height } } elseif ($textboxHeight.Focused) { if ([int32]::TryParse($textboxHeight.Text, [ref]$null) ) { $width = [int]($textboxHeight.Text) * $global:originalWidth.Value / $global:originalHeight.Value $textboxWidth.Text = [string]$width } } } } $mainForm = New-Object System.Windows.Forms.Form.Form $mainForm Text = 'Image Resizer' $mainForm.Width = 400 $mainForm.Height = 250 $labelDropImage = New-Object FileDropLabel $labelDropImage.Text = 'Drag and drop an image here' $labelDropImage.Size = New-Object System.Drawing.Size(350, ) $labelDropImage.Location = New-Object System.Drawing.Point(20, 20) $labelDropImage.BackColor = [System.Drawing.SystemColors]::ControlLight $labelDropImage.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter $labelDropImage.BorderStyle = [System.Windows.Forms.BorderStyle]::FixedSingle $labelDropImage.Add_DragDrop({ $files = $_.Data.GetData([Windows.Forms.DataFormats]::FileDrop) if ($files.Count -eq 1 -and [System.IO .File]::Exists($files[0])) { $imageExtensions = @('.jpg', '.jpeg', '.png', '.bmp', '.gif') $fileExtension = [System.IO. Path]::GetExtension($files[0]).ToLower() if ($imageExtensions -contains $fileExtension) { $originalImage = [System.Drawing.Image]::FromFile($files[0]) $global:originalWidth.Value = $originalImage.Width $global:originalHeight.Value = $originalImage.Height $textboxWidth.Text = $global:originalWidth.Value $textboxHeight.Text = $global:originalHeight.Value $global:inputImagePath.Value = $files[0].ToString() $labelDropImage.Text = $global:inputImagePath.Value } else { [System.Windows.Forms.MessageBox]::Show('Unsupported image format.', 'Error', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]: :Error) } } }) $mainForm.Controls.Add($labelDropImage) $labelWidth = New-Object System.Windows.Forms.Label $labelWidth.Text = 'Width:' $labelWidth.Location = New-Object System.Drawing.Point(20, 80) $labelWidth.Size = New-Object System.Drawing.Size(50, 20) $mainForm.Controls.Add($labelWidth) $textboxWidth = New-Object System.Windows.Forms.TextBox $textboxWidth.Location = New-Object System.Drawing. Point(80, 80) $textboxWidth.Size = New-Object System.Drawing.Size(50, 20) # $textboxWidth.Add_Leave({ UpdateAspectRatio }) $textboxWidth.Add_TextChanged({ UpdateAspectRatio }) $mainTPidForm.Controls.Text( New-Object System.Windows.Forms.Label $labelHeight.Text = 'Height:' $labelHeight.Location = New-Object System.Drawing.Point(150, 80) $labelHeight.Size = New-Object System.Drawing.Size(50, 20) $mainForm.Controls.Add($labelHeight) $textboxHeight = New-Object System.Windows.Forms.TextBox $textboxHeight.Location = New-Object System.Drawing.Point(210, 80) $textboxHeight.Size = New-Object System.Drawing. Size(50, 20) # $textboxHeight.Add_Leave({ UpdateAspectRatio }) $textboxHeight.Add_TextChanged({ UpdateAspectRatio }) $mainForm.Controls.Add($textboxHeight) $checkboxMaintainAspectRatio = New-Object System.Windows.Forms.CheckBox $checkboxMaintainAspectRatio.Text = 'Maintain Aspect Ratio' $checkboxMaintainAspectRatio.Location = New-Object System.Drawing.Point(20, 110) $checkboxMaintainAspectRatio.Checked = $true $mainForm.Controls.Add($checkboxMaintainAspectRatio) $buttonResize = New-ResTPObject System.Windows.Forms' Image' $buttonResize.Location = New-Object System.Drawing.Point(20, 140) $buttonResize.Size = New-Object System.Drawing.Size(100, 30) $buttonResize.Add_Click({ if (-not [string]:: $resizeCommand = "magick `"$($global:inputImagePath.Value)`" -resize $($textboxWidth.Text)`x$($textboxHeight.Text) `"$($outputImagePath)`"" try { $resizeResult = Invoke-Expression -Command $resizeCommand [ System.Windows.Forms.MessageBox]::Show("Image resized and saved as `n$outputImagePath", 'Success', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]:: Information) } catch { $errorMessage = $_.Exception.Message [System.Windows.Forms.MessageBox]::Show("Error occurred during resizing: `n$errorMessage", 'Error', [System.Windows.Forms.MessageBoxButtons]:: OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } else { [System.Windows.Forms.MessageBox]::Show('Please drag and drop an image to be resized.', 'Error', [ System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } }) $mainForm.Controls.Add($buttonResize) $mainForm.Add_Closing({ $mainForm.Dispose() }) [void ][System.Windows.Forms.Application]::EnableVisualStyles() [void][System.Windows.Forms.Application]::Run($mainForm)

full dialogue

Hollen9

I want you to help me make a powershell gui program. You don’t need to explain the principle to me. I just need the code. The interface of the program should be in English, and the comments of the program should also be written in English; but you and I must use Taiwan throughout the answer traditional Chinese.

Drag the picture to the gui, and the picture size will be scaled according to the user's needs. The user can check whether to keep the aspect ratio. If it is kept, one side of the length or width field will be automatically adjusted to the straight corresponding to the original ratio.

I hope to support all mainstream image formats, but the most important thing is to be able to preserve the gif animation, scale it and save it to the source folder.

GPT4

Ok, check out the PowerShell GUI code below. This program will make a picture resizing tool according to your request, and support to preserve GIF animation. Note that ImageMagick needs to be installed to handle image scaling and preserve animations.

please install first ImageMagick, and add it to your system environment variables.

Add-Type -AssemblyName System.Windows.Forms Add-Type -TypeDefinition @" using System; using System.Windows.Forms; public class FileDropLabel : Label { public FileDropLabel() { AllowDrop = true; DragEnter += (s, e) => { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; }; } } "@ function UpdateAspectRatio { if ($checkboxMaintainAspectRatio.Checked) { if ($textboxWidth.Focused) { $height = [ int]($textboxWidth.Text) * $originalHeight / $originalWidth $textboxHeight.Text = [math]::Round($height) } elseif ($textboxHeight.Focused) { $width = [int]($textboxHeight.Text) * 1TP3WTP1thToriginalWidth / 1ightTP3 [math]::Round($width) } } } $mainForm = New-Object System.Windows.Forms.Form $mainForm.Text = 'Image Resizer' $mainForm.Width = 400 $mainForm.Height = 250 $labelDropImage = New-Object FileDropLabel $labelDropImage Text = 'Drag and drop an image here' $labelDropImage.Size = New-Object System.Drawing.Size(350, 50) $labelDropImage.Location = New-Object System.Drawing.Point(20, 20) $labelDropImage.BackColor = [System .Drawing.SystemColors]::ControlLight $labelDropImage.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter $labelDropImage.BorderStyle = [System.Windows.Forms.BorderStyle]::FixedSingle $labelDropImage.Add_DragDrop({ $files = $_.Data.GetData ([Windows.Forms.DataFormats]::FileDrop) if ($files.Count -eq 1 -and [System.IO.File]::Exists($files[0])) { $imageExtensions = @('.jpg', ' .jpeg', '.png', '.bmp', '.gif') $fileExtension = [System.IO.Path]::GetExtension($files[0]).ToLower() if ($imageExtensions -contains $fileExtension) { $originalImage = [System.Drawing.Image]::FromFile($files[0]) $originalWidth = $originalImage.Width $originalHeight = $originalImage.Height $textboxWidth.Text = $originalWidth $textboxHeight.Text = $originalHeight $inputImagePath = $files[0] $labelDropImage.Text = $inputImagePath } else { [System.Windows.Forms.MessageBox]::Show('Unsupported image format.', 'Error', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error ) } } }) $mainForm.Controls.Add($labelDropImage) $labelWidth = New-Object System.Windows.Forms.Label $labelWidth.Text = 'Width:' $labelWidth.Location = New-Object System.Drawing.Point(20, 80) $mainForm.Controls.Add($labelWidth) $text

Hollen9

Please continue, from
‵‵‵
$mainForm.Controls.Add($labelDropImage)

$labelWidth = New-Object System.Windows.Forms.Label
$labelWidth.Text = 'Width:'
$labelWidth.Location = New-Object System.Drawing.Point(20, 80)
$mainForm.Controls.Add($labelWidth)
‵‵‵
continue

GPT4

Ok, please refer to the following code:

$textboxWidth = New-Object System.Windows.Forms.TextBox $textboxWidth.Location = New-Object System.Drawing.Point(80, 80) $textboxWidth.Size = New-Object System.Drawing.Size(50, 20) $textboxWidth.Add_Leave( { UpdateAspectRatio }) $mainForm.Controls.Add($textboxWidth) $labelHeight = New-Object System.Windows.Forms.Label $labelHeight.Text = 'Height:' $labelHeight.Location = New-Object System.Drawing.Point(150, 80) $mainForm .Controls.Add($labelHeight) $textboxHeight = New-Object System.Windows.Forms.TextBox $textboxHeight.Location = New-Object System.Drawing.Point(210, 80) $textboxHeight.Size = New-Object System.Drawing.Size(50 , 20) $textboxHeight.Add_Leave({ UpdateAspectRatio }) $mainForm.Controls.Add($textboxHeight) $checkboxMaintainAspectRatio = New-Object System.Windows.Forms.CheckBox $checkboxMaintainAspectRatio.Text = 'Maintain Aspect Ratio' $checkboxMaintainAspectRatio.Location = New-Object System.Drawing .Point(20, 110) $checkboxMaintainAspectRatio.Checked = $true $mainForm.Controls.Add($checkboxMaintainAspectRatio) $buttonResize = New-Object System.Windows.Forms.Button $buttonResize.Text = 'Resize Image' $buttonResize = New-LocationObject .Point(20, 140) $buttonResize.Size = New-Object System.Drawing.Size(100, 30) $buttonResize.Add_Click({ if (-not [string]::IsNullOrEmpty($inputImagePath)) { $outputImagePath = [System.IO .Path]::ChangeExtension($inputImagePath, '_resized' + [System.IO.Path]::GetExtension($inputImagePath)) $resizeCommand = "magick `"$inputImagePath`" -resize $textboxWidth.Text`x$textboxHeight.Text ""$outputImagePath " try { $resizeResult = Invoke-Expression -Command $resizeCommand [System.Windows.Forms.MessageBox]::Show("Image resized and saved as `n$outputImagePath", 'Success', [System.Windows.Forms.MessageBoxButtons]::OK , [System.Windows.Forms.MessageBoxIcon]::Information) } catch { [System.Windows.Forms.MessageBox]::Show('Error occurred during resizing.', 'Error', [System.Windows.Forms.MessageBoxButtons ]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } else { [System.Windows.Forms.MessageBox]::Show('Please drag and drop an image to be resized.', 'Error ', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } }) $mainForm.Controls.Add($buttonResize) $mainForm.Add_Closing({ $mainForm.Dispose() } ) [void][System.Windows.Forms.Application]::Run($mainForm)

This code continues to create the graphical interface, including label and text boxes for width, height, checkboxes to maintain aspect ratio, and buttons to perform zoom operations. When the user drags an image to the interface and clicks the "Resize Image" button, the image will be scaled using ImageMagick and the result will be saved to the source folder.

Hollen9

I can see the window GUI when the program is executed, but the console of powershell reports an error:

PS C:\Users\Hollen9> . 'c:\Program Files (Portable)\SomePowershell\ImageResize - DEV.ps1' Add-Type : c:\Users\Hollen9\AppData\Local\Temp\gsrfdomm.0.cs( 2) : The type or namespace name 'Forms' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?) c:\Users\Hollen9\AppData\Local\Temp\gsrfdomm.0.cs( 1) : using System; c:\Users\Hollen9\AppData\Local\Temp\gsrfdomm.0.cs(2) : >>> using System.Windows.Forms; c:\Users\Hollen9\AppData\Local\Temp \gsrfdomm.0.cs(3) : At C:\Program Files (Portable)\SomePowershell\ImageResize - DEV.ps1:2 char:1 + Add-Type -TypeDefinition @" + ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidData: (Microsoft.Power...peCompilerError:AddTypeCompilerError) [Add-Type], Exception + FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell. Commands.AddTypeCommand Add-Type : c:\Users\Hollen9\AppData\Local\Temp\gsrfdomm.0.cs(4) : The type or namespace name 'Label' could not be found (are you missing a using directive or an assembly reference?) c:\Users\Hollen9\AppData\Local\Temp\gsrfdomm.0.cs(3) : c:\Users\Hollen9\AppData\Local\Temp\gsrfdomm.0.cs(4) : >> > public class FileDropLabel : Label c:\Users\Hollen9\AppData\Local\Temp\gsrfdomm.0.cs(5) : { At C:\Program Files (Portable)\SomePowershell\ImageResize - DEV.ps1:2 char: 1 + Add-Type -TypeDefinition @" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo : InvalidData: (Microsoft.Power...peCompilerError :AddTypeCompilerError) [Add-Type], Exception + FullyQualifiedErrorId : SOURCE_CODE_ERROR,Microsoft.PowerShell.Commands.AddTypeCommand Add-Type : Cannot add type. Compilation errors occurred. At C:\Program Files (Portable)\SomePowershell\ImageResize - DEV. ps1:2 char:1 + Add-Type -TypeDefinition @" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo : InvalidData: (:) [Add-Type], InvalidOperationException + FullyQualifiedErrorId : COMPILER_ERRORS,Microsoft.PowerShell.Commands.AddTypeCommand New-Object : Cannot find type [FileDropLabel]: verify that the assembly containing this type is loaded. At C:\Program Files (Portable)\ SomePowershell\ImageResize - DEV.ps1:36 char:19 + $labelDropImage = New-Object FileDropLabel + ~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo : InvalidType: ( :) [New-Object], PSArgumentException + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand The property 'Text' cannot be found on this object. Verify that the property exists and can be set. At C:\Program Files ( Portable)\SomePowershell\ImageResize - DEV.ps1:37 char:1 + $labelDropImage.Text = 'Drag and drop an image here' + ~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : PropertyNotFound The property ' Size' cannot be found on this object. Verify that the property exists and can be set. At C:\Program Files (Portable)\SomePowershell\ImageResize - DEV.ps1:38 char:1 + $labelDropImage.Size = New-Object System .Drawing.Size(350, 50) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : PropertyNotFound The property 'Location' cannot be found on this object. Verify that the property exists and can be set. At C:\Program Files (Portable)\SomePowershell\ImageResize - DEV.ps1:39 char:1 + $labelDropImage.Location = New-Object System.Drawing.Point(20, 20) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : PropertyNotFound The property 'BackColor' cannot be found on this object. Verify that the property exists and can be set. At C:\Program Files (Portable)\SomePowershell\ImageResize - DEV.ps1:40 char:1 + $labelDropImage.BackColor = [System.Drawing.SystemColors]::ControlLig ... + ~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : PropertyNotFound The property 'TextAlign' cannot be found on this object. Verify that the property exists and can be set. At C:\Program Files (Portable)\SomePowershell\ImageResize - DEV.ps1:41 char:1 + $labelDropImage.TextAlign = [System.Drawing.ContentAlignment]::Middle ... + ~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : PropertyNotFound The property 'BorderStyle' cannot be found on this object. Verify that the property exists and can be set .At C:\Program Files (Portable)\SomePowershell\ImageResize - DEV.ps1:42 char:1 + $labelDropImage.BorderStyle = [System.Windows.Forms.BorderStyle]::Fix ... + ~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : PropertyNotFound You cannot call a method on a null-valued expression. At C:\Program Files (Portable) \SomePowershell\ImageResize - DEV.ps1:43 char:1 + $labelDropImage.Add_DragDrop({ + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull

GPT4

Sorry for the problem in the previous answer. Please use the following corrected code:

Add-Type -AssemblyName System.Windows.Forms Add-Type -TypeDefinition @" using System; using System.Windows.Forms; public class FileDropLabel : Label { public FileDropLabel() { AllowDrop = true; DragEnter += (s, e) => { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; }; } } "@ -ReferencedAssemblies @('System.Windows.Forms.dll', 'System.Drawing.dll ') # Omit the same part as the previous code... [void][System.Windows.Forms.Application]::EnableVisualStyles() [void][System.Windows.Forms.Application]::Run($mainForm)

This correction will be in Add-Type Parameters added to the directive -ReferencedAssemblies to reference the required components and added the last line [void][System.Windows.Forms.Application]::EnableVisualStyles() to apply the theme styles. Make sure to run this program as an administrator in PowerShell to avoid permission issues.

Hollen9

The Label width of Weight and Height is too wide, covering the Textbox on the right

GPT4

Sorry for the inconvenience, please send $labelWidth and $labelHeight of size properties to adjust to avoid overlapping adjacent controls. Please refer to the modified code below:

$labelWidth = New-Object System.Windows.Forms.Label $labelWidth.Text = 'Width:' $labelWidth.Location = New-Object System.Drawing.Point(20, 80) $labelWidth.Size = New-Object System.Drawing.Size( 50, 20) # modified Size property $mainForm.Controls.Add($labelWidth) $labelHeight = New-Object System.Windows.Forms.Label $labelHeight.Text = 'Height:' $labelHeight.Location = New-Object System.Drawing.Point (150, 80) $labelHeight.Size = New-Object System.Drawing.Size(50, 20) # Modified Size property $mainForm.Controls.Add($labelHeight) # Omit the same part as the previous code...

This should avoid coverage issues. Be sure to adjust the position and size of other controls as needed.

Hollen9

I found that when I haven't dragged the picture into it, the following error will appear when I modify the size:

Attempted to divide by zero. At C:\Program Files (Portable)\SomePowershell\ImageResize - DEV.ps1:25 char:13 + $width = [int]($textboxHeight.Text) * $originalWidth / $o ... + ~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~ + CategoryInfo : NotSpecified: (:) [], RuntimeException + FullyQualifiedErrorId : RuntimeException

The program can still continue to execute.

GPT4

Sorry for the confusion. This is because before dragging the image, 1TP3 Original Width and 1TP3OriginalHeight value of zero. To solve this problem, you can use the UpdateAspectRatio Add a condition at the beginning of the function, check 1TP3 Original Width and 1TP3OriginalHeight Is it greater than zero. Please refer to the modified code below:

function UpdateAspectRatio { if ($checkboxMaintainAspectRatio.Checked -and $originalWidth -gt 0 -and $originalHeight -gt 0) { if ($textboxWidth.Focused) { $height = [int]($textboxWidth.Text) * $originalHeight / $originalWidth $textboxHeight.Text = [string] $height } elseif ($textboxHeight.Focused) { $width = [int]($textboxHeight.Text) * $originalWidth / $originalHeight $textboxWidth.Text = [string]$width } } } # Omit the same part as the previous code...

In this way, when the image has not been dragged, modifying the size will not trigger an error.

Hollen9

I found that $originalWidth and $originalHeight do have the correct values when the picture is dragged in, but when I let the long or wide textbox go to focus, $originalWidth and $originalHeight are both ""
.

GPT4

Sorry, this is because 1TP3 Original Width and 1TP3OriginalHeight exist UpdateAspectRatio Used as a local variable inside the function, resulting in UpdateAspectRatio Their values cannot be accessed within the function. To fix this, set the 1TP3 Original Width and 1TP3OriginalHeight defined as a global variable, and in Add_DragDrop Event handlers update their values. Here is the modified code:

$originalWidth = 0 $originalHeight = 0 $labelDropImage.Add_DragDrop({ $files = $_.Data.GetData([System.Windows.Forms.DataFormats]::FileDrop) if ($files -and $files.Count -gt 0) { $filePath = [0TP3T ] $image = [System.Drawing.Image]::FromFile($filePath) $textboxHeight.Text = $image.Width $originalHeight = $image.Height $textboxWidth.Text = [string]$originalWidth $textboxHeight.Text = [string]1TP3}ToriginalHeight and 1TP3}T4}) The same part of the code...

This should fix it 1TP3 Original Width and 1TP3OriginalHeight exist UpdateAspectRatio Inaccessible problem in function.

Hollen9

In short, my program is now as follows, and the two variables of UpdateAspectRatio are still 0.

Add-Type -AssemblyName System.Windows.Forms Add-Type -TypeDefinition @" using System; using System.Windows.Forms; public class FileDropLabel : Label { public FileDropLabel() { AllowDrop = true; DragEnter += (s, e) => { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; }; } } "@ -ReferencedAssemblies @('System.Windows.Forms.dll', 'System.Drawing.dll ') $originalWidth = 0 $originalHeight = 0 function UpdateAspectRatio { if ($checkboxMaintainAspectRatio.Checked -and $originalWidth -gt 0 -and $originalHeight -gt 0) { if ($textboxWidth.Focused) { $height = [int]($textboxWidth.Text) * $originalHeight / $originalWidth $textboxHeight.Text = [string]$height } elseif ($textboxHeight.Focused) { $width = [int]($textboxHeight.Text) * $originalWidth / $originalHeight $textboxWidth.Text = [string]$}mFor.1Windows .Forms.Form $mainForm.Text = 'Image Resizer' $mainForm.Width = 400 $mainForm.Height = 250 $labelDropImage = New-Object FileDropLabel $labelDropImage.Text = 'Drag and drop an image here' $labelDropingObject.Size = New-Object .Size(350, 50) $labelDropImage.Location = New-Object System.Drawing.Point(20, 20) $labelDropImage.BackColor = [System.Drawing.SystemColors]::ControlLight $labelDropImage.TextAlign = [System.Drawing.ContentAlignment]: :MiddleCenter $labelDropImage.BorderStyle = [System.Windows.Forms.BorderStyle]::FixedSingle $labelDropImage.Add_DragDrop({ $files = $_.Data.GetData([Windows.Forms.DataFormats]::FileDrop) if ($files.Count -eq 1 -and [System.IO.File]::Exists($files[0])) { $imageExtensions = @('.jpg', '.jpeg', '.png', '.bmp', '.gif') $fileExtension = [System.IO.Path]::GetExtension($files[0]).ToLower() if ($imageExtensions -contains $fileExtension) { $originalImage = [System.Drawing.Image]::FromFile($files[0]) $originalWidth = $originalImage .Width $originalHeight = $originalImage.Height $textboxWidth.Text = $originalWidth $textboxHeight.Text = $originalHeight $inputImagePath = $files[0] $labelDropImage.Text = $inputImagePath } else { [System.Windows.Forms.MessageBox]::Show('Unsupported image format.' , 'Error', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } }) $mainForm.Controls.Add($labelDropImage) $labelWidth = New-Object System. Windows.Forms.Label $labelWidth.Text = 'Width:' $labelWidth.Location = New-Object System.Drawing.Point(20, 80) $labelWidth.Size = New-Object System.Drawing.Size(50, 20) $mainForm.Controls .Add($labelWidth) $textboxWidth = New-Object System.Windows.Forms.TextBox $textboxWidth.Location = New-Object System.Drawing.Point(80, 80) $textboxWidth.Size = New-Object System.Drawing.Size(50, 20 ( 150, 80) $labelHeight.Size = New-Object System.Drawing.Size(50, 20) $mainForm.Controls.Add($labelHeight) $textboxHeight = New-Object System.Windows.Forms.TextBox $textboxHeight.Location = New-Object System. Drawing.Point(210, 80) $textboxHeight.Size = New-Object System.Drawing.Size(50, 20) $textboxHeight.Add_Leave({ UpdateAspectRatio }) $mainForm.Controls.Add($textboxHeight) $checkboxMaintainAspectRatio = New-Object System.Windows Forms.CheckBox $checkboxMaintainAspectRatio.Text = 'Maintain Aspect Ratio' $checkboxMaintainAspectRatio.Location = New-Object System.Drawing.Point(20, 110) $checkboxMaintainAspectRatio.Checked = $true $mainForm.Controls.Add($checkboxMaintainAspectRatio) $buttonResize = New-Object System.Windows .Forms.Button $buttonResize.Text = 'Resize Image' $buttonResize.Location = New-Object System.Drawing.Point(20, 140) $buttonResize.Size = New-Object System.Drawing.Size(100, 30) $buttonResize.Add_Click( { if (-not [string]::IsNullOrEmpty($inputImagePath)) { $outputImagePath = [System.IO.Path]::ChangeExtension($inputImagePath, '_resized' + [System.IO.Path]::GetExtension($inputImagePath)) $resizeCommand = "magick `"$inputImagePath`" -resize $textboxWidth.Text`x$textboxHeight.Text `"$outputImagePath`"" try { $resizeResult = Invoke-Expression -Command $resizeCommand [System.Windows.Forms.MessageBox]::Show("Image resized and saved as `n$outputImagePath", 'Success', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) } catch { [System.Windows.Forms.MessageBox]:: Show('Error occurred during resizing.', 'Error', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } else { [System.Windows.Forms .MessageBox]::Show('Please drag and drop an image to be resized.', 'Error', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } }) $mainForm.Controls.Add($buttonResize) $mainForm.Add_Closing({ $mainForm.Dispose() }) [void][System.Windows.Forms.Application]::EnableVisualStyles() [void][System.Windows.Forms. Application]::Run($mainForm)

GPT4

Thank you for your feedback. I noticed that you use Add_Leave event, but it only fires when leaving the input box. To resolve this issue, replace the original Add_Leave event changed to Add_TextChanged event. That way, when you modify the width or height, it immediately updates the other value, maintaining the aspect ratio.

Modified code:

$textboxWidth.Add_TextChanged({ UpdateAspectRatio }) $mainForm.Controls.Add($textboxWidth) # ... $textboxHeight.Add_TextChanged({ UpdateAspectRatio }) $mainForm.Controls.Add($textboxHeight)

After this modification, it should be possible to update another value immediately when the width or height is modified in the input box, and keep the aspect ratio. Note that if you enter non-numeric characters in the input box, errors may result. If you need to prevent the entry of non-numeric characters, you can further modify the script to check the input value.

Hollen9

This modification is not bad, I also want to do it. But you didn't understand my question:
I say it is always zero because the $originalWidth and $originalHeight accessed in the Drop event are regional variables, and the UpdateAspectRatio() in different Scopes cannot obtain the new value of the variable, so it will always be the initially declared 0

GPT4

Sorry, I misunderstood. Please send 1TP3 Original Width and 1TP3OriginalHeight In place of global variables, they can be defined as [ref] types so that they can be accessed and modified in multiple categories.

Please replace the following code:

$originalWidth = 0 $originalHeight = 0

Replace with:

$global:originalWidth = [ref]0 $global:originalHeight = [ref]0

Then, in UpdateAspectRatio function and drag and drop events, use $global: originalWidth. Value and $global:originalHeight.Value replace 1TP3 Original Width and 1TP3OriginalHeight.

The following is the modified UpdateAspectRatio Functions and drag and drop events:

function UpdateAspectRatio { if ($checkboxMaintainAspectRatio.Checked -and $global:originalWidth.Value -gt 0 -and $global:originalHeight.Value -gt 0) { if ($textboxWidth.Focused) { $height = [int]($gltext.Textbox) * originalHeight.Value / $global:originalWidth.Value $textboxHeight.Text = [string]$height } elseif ($textboxHeight.Focused) { $width = [int]($textboxHeight.Text) * $global:originalWidth.Value / $globalTglobalight.Text3 = [string]$width } } } $labelDropImage.Add_DragDrop({ $files = $_.Data.GetData([Windows.Forms.DataFormats]::FileDrop) if ($files.Count -eq 1 -and [System.IO.File]: :Exists($files[0])) { $imageExtensions = @('.jpg', '.jpeg', '.png', '.bmp', '.gif') $fileExtension = [System.IO.Path]:: GetExtension($files[0]).ToLower() if ($imageExtensions -contains $fileExtension) { $originalImage = [System.Drawing.Image]::FromFile($files[0]) $global:originalWidth.Value = $originalImage.Width 1TP3originalHealthal: Value = $originalImage.Height $textboxWidth.Text = $global:originalWidth.Value $textboxHeight.Text = $global:originalHeight.Value $inputImagePath = $files[0] $labelDropImage.Text = $input. 'Unsupported image format.', 'Error', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } })

Now when you modify width or height,UpdateAspectRatio function should be able to read and update correctly $global: originalWidth. Value and $global:originalHeight.Value.

Hollen9

The problem of length and width is solved, but I found that variables such as $inputImagePath have similar problems

GPT4

for $inputImagePath, you can use the same 1TP3 Original Width and 1TP3OriginalHeight Same solution. Will $inputImagePath defined as global [ref] variable, and use the $global:inputImagePath.Value access and modify it.

First, put the following code:

$inputImagePath = ""

Replace with:

$global:inputImagePath = [ref] ""

Then in drag and drop events and button click events, use $global:inputImagePath.Value replace $inputImagePath.

Here are the modified drag and drop events and button click events:

$labelDropImage.Add_DragDrop({ $files = $_.Data.GetData([Windows.Forms.DataFormats]::FileDrop) if ($files.Count -eq 1 -and [System.IO.File]::Exists($files[0]) ) { $imageExtensions = @('.jpg', '.jpeg', '.png', '.bmp', '.gif') $fileExtension = [System.IO.Path]::GetExtension($files[0]). ToLower() if ($imageExtensions -contains $fileExtension) { $originalImage = [System.Drawing.Image]::FromFile($files[0]) $global:originalWidth.Value = $originalImage.Width $global:originalHeight.TextHeightValue1TP3.ightTorigin = $global:originalWidth.Value $textboxHeight.Text = $global:originalHeight.Value $global:inputImagePath.Value = $files[0] $labelDropImage.Text = $global:inputImagePath.Value } else { [System.Windows.Forms].Message 'Unsupported image format.', 'Error', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } }) $buttonResize.Add_Click({ if (-not [string]::IsNullOrEmpty($global:inputImagePath.Value)) { $outputImagePath = [System.IO.Path]::ChangeExtension($global:inputImagePath.Value, '_resized' + [System.IO.Path]::GetExtension($global :inputImagePath.Value)) $resizeCommand = "magick `"$global:inputImagePath.Value`" -resize $textboxWidth.Text`x$textboxHeight.Text `"$outputImagePath`"" try { $resizeResult = Invoke-Expression -Command $resizeCommand [System.Windows .MessageBox]::Show("Image resized and saved as `n$outputImagePath", 'Success', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) } catch { [System.Windows.Forms.MessageBox]::Show('Error occurred during resizing.', 'Error', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error ) } } else { [System.Windows.Forms.MessageBox]::Show('Please drag and drop an image to be resized.', 'Error', [System.Windows.Forms.MessageBoxButtons]::OK, [System .Windows.Forms.MessageBoxIcon]::Error) } })

Now,$global:inputImagePath.Value Should be properly accessed and modified as needed.

Hollen9

catch {

    }

How do I change it to something like e.Message that can display error messages

GPT4

to be wrong

Hollen9

There was an error in OpenAI just now, I saw your answer looks like this:

to be wrong

GPT4

Sorry for the truncated answer. Here is the full answer:

To display a specific error message in an error dialog, you can use $_ variable to get details about the current error. exist catch block, you can use Exception. Message properties to get more information about the exception. You can modify the catch block to display the error message, as follows:

catch { $errorMessage = $_.Exception.Message [System.Windows.Forms.MessageBox]::Show("Error occurred during resizing: `n$errorMessage", 'Error', [System.Windows.Forms.MessageBoxButtons]::OK, [ System.Windows.Forms.MessageBoxIcon]::Error) }

This will display the error message for the current exception in an error dialog.

Hollen9

I see a MsgBox showing success, but no real success (no new image file)
And the Console prints the following message:

magick.exe: unable to open image 'System.Management.Automation.PSReference1[System.String].Value': No such file or directory @ error/blob.c/OpenBlob/3569. magick.exe: unable to open module file 'C:\Program Files\ImageMagick\modules\coders\IM_MOD_RL_VALUE_.dll': No such file or directory @ warning/module.c/GetMagickModulePath/677. magick.exe: no decode delegate for this image format `VALUE' @ error /constitute.c/ReadImage/746.

GPT4

This error is due to incorrect variable references on the command line. You need to add $inputImagePath and $outputImagePath The value of the variable is passed directly to the magick Order. please modify $buttonResize.Add_Click The script block is as follows:

$buttonResize.Add_Click({ if (-not [string]::IsNullOrEmpty($global:inputImagePath)) { $outputImagePath = [System.IO.Path]::ChangeExtension($global:inputImagePath, '_resized' + [System.IO.Path] ::GetExtension($global:inputImagePath)) $resizeCommand = "magick `"$($global:inputImagePath)`" -resize $($textboxWidth.Text)`x$($textboxHeight.Text) `"$($outputImagePath)`1"TP" try = Invoke-Expression -Command $resizeCommand [System.Windows.Forms.MessageBox]::Show("Image resized and saved as `n$outputImagePath", 'Success', [System.Windows.Forms.MessageBoxButtons]::OK, [System. Windows.Forms.MessageBoxIcon]::Information) } catch { $errorMessage = $_.Exception.Message [System.Windows.Forms.MessageBox]::Show("Error occurred during resizing: `n$errorMessage", 'Error', [System. Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } else { [System.Windows.Forms.MessageBox]::Show('Please drag and drop an image to be resized .', 'Error', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } })

This should do the trick. Make sure you are using global: modifier to access global variables.

Hollen9

Cannot convert value "\" to type "System.Int32". Error: "Input string was not in a correct format." At C:\Program Files (Portable)\SomePowershell\ImageResize - DEV.ps1:27 char:13 + $height = [int]($textboxWidth.Text) * $global:originalHei ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [], RuntimeException + FullyQualifiedErrorId : InvalidCastFromStringToInteger Cannot convert value "\" to type " System.Int32". Error: "Input string was not in a correct format." At C:\Program Files (Portable)\SomePowershell\ImageResize - DEV.ps1:27 char:13 + $height = [int]($textboxWidth.Text ) * $global:originalHei ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [], RuntimeException + FullyQualifiedErrorId : InvalidCastFromStringToInteger magick.exe: unable to open image 'System.Management.Automation.PSReference1[System .String]': No such file or directory @ error/blob.c/OpenBlob/3569. magick.exe: no decode delegate for this image format `' @ error/constitute.c/ReadImage/746.

All my programs now look like this:

Add-Type -AssemblyName System.Windows.Forms Add-Type -TypeDefinition @" using System; using System.Windows.Forms; public class FileDropLabel : Label { public FileDropLabel() { AllowDrop = true; DragEnter += (s, e) => { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; }; } } "@ -ReferencedAssemblies @('System.Windows.Forms.dll', 'System.Drawing.dll ') $global:originalWidth = [ref]0 $global:originalHeight = [ref]0 $global:inputImagePath = [ref]"" function UpdateAspectRatio { if ($checkboxMaintainAspectRatio.Checked -and $global:originalWidth1TP -Value1TP -value -gt .Value -gt 0) { if ($textboxWidth.Focused) { $height = [int]($textboxWidth.Text) * $global:originalHeight.Value / $global:originalWidth.Value $textboxHeight.Text = [string]$height } elseif ($textedHeight ) { $width = [int]($textboxHeight.Text) * $global:originalWidth.Value / $global:originalHeight.Value $textboxWidth.Text = [string]$width } } } $mainForm = New-Object System.Windows.Forms.Form $mainForm = 'Image Resizer' $mainForm.Width = 400 $mainForm.Height = 250 $labelDropImage = New-Object FileDropLabel $labelDropImage.Text = 'Drag and drop an image here' $labelDropImage.Size = New-Object System.Drawing.Size(350, 5) $labelDropImage.Location = New-Object System.Drawing.Point(20, 20) $labelDropImage.BackColor = [System.Drawing.SystemColors]::ControlLight $labelDropImage.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter $labelDropImage.BorderStyle = [ System.Windows.Forms.BorderStyle]::FixedSingle $labelDropImage.Add_DragDrop({ $files = $_.Data.GetData([Windows.Forms.DataFormats]::FileDrop) if ($files.Count -eq 1 -and [System.IO. File]::Exists($files[0])) { $imageExtensions = @('.jpg', '.jpeg', '.png', '.bmp', '.gif') $fileExtension = [System.IO.Path ]::GetExtension($files[0]).ToLower() if ($imageExtensions -contains $fileExtension) { $originalImage = [System.Drawing.Image]::FromFile($files[0]) $global:originalWidth.Value = $originalImage.Width $gl :originalHeight.Value = $originalImage.Height $textboxWidth.Text = $global:originalWidth.Value $textboxHeight.Text = $global:originalHeight.Value $global:inputImagePath.Value = $files[0] $labelDropImage.Text = $global:inputImagePath.Value } else { [System .Windows.Forms.MessageBox]::Show('Unsupported image format.', 'Error', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } }) $mainForm.Controls.Add($labelDropImage) $labelWidth = New-Object System.Windows.Forms.Label $labelWidth.Text = 'Width:' $labelWidth.Location = New-Object System.Drawing.Point(20, 80) $labelWidth.Size = New-Object System.Drawing.Size(50, 20) $mainForm.Controls.Add($labelWidth) $textboxWidth = New-Object System.Windows.Forms.TextBox $textboxWidth.Location = New-Object System.Drawing.Point(80, 80 ) $textboxWidth.Size = New-Object System.Drawing.Size(50, 20) # $textboxWidth.Add_Leave({ UpdateAspectRatio }) $textboxWidth.Add_TextChanged({ UpdateAspectRatio }) $mainForm.Controls.AddTP($textight1Width3Object) Windows.Forms.Label $labelHeight.Text = 'Height:' $labelHeight.Location = New-Object System.Drawing.Point(150, 80) $labelHeight.Size = New-Object System.Drawing.Size(50, 20) $mainForm.Controls .Add($labelHeight) $textboxHeight = New-Object System.Windows.Forms.TextBox $textboxHeight.Location = New-Object System.Drawing.Point(210, 80) $textboxHeight.Size = New-Object System.Drawing.Size(50, 20 ) # $textboxHeight.Add_Leave({ UpdateAspectRatio }) $textboxHeight.Add_TextChanged({ UpdateAspectRatio }) $mainForm.Controls.Add($textboxHeight) $checkboxMaintainAspectRatio = New-Object System.Windows.Forms.CheckBox $checkboxMaintainAspectRatio.Text = 'Maintain Aspect Ratio' $checkboxMaintainAspectRatio.Location = New-Object System.Drawing.Point(20, 110) $checkboxMaintainAspectRatio.Checked = $true $mainForm.Controls.Add($checkboxMaintainAspectRatio) $buttonResize = New-Object System.Windows.Forms.Button $buttonResize.LocLocLocText = 'Resize3Tbutton Image' = New-Object System.Drawing.Point(20, 140) $buttonResize.Size = New-Object System.Drawing.Size(100, 30) $buttonResize.Add_Click({ if (-not [string]::IsNullOrEmpty($global:inputImagePath )) { $outputImagePath = [System.IO.Path]::ChangeExtension($global:inputImagePath, '_resized' + [System.IO.Path]::GetExtension($global:inputImagePath)) $resizeCommand = "magick `" $($global: inputImagePath)`" -resize $($textboxWidth.Text)`x$($textboxHeight.Text) `"$($outputImagePath)`"" try { $resizeResult = Invoke-Expression -Command $resizeCommand [System.Windows.Forms.MessageBox]::Show ("Image resized and saved as `n$outputImagePath", 'Success', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) } catch { $errorMessage = $_.Exception. Message [System.Windows.Forms.MessageBox]::Show("Error occurred during resizing: `n$errorMessage", 'Error', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon] ::Error) } } else { [System.Windows.Forms.MessageBox]::Show('Please drag and drop an image to be resized.', 'Error', [System.Windows.Forms.MessageBoxButtons]::OK , [System.Windows.Forms.MessageBoxIcon]::Error) } }) $mainForm.Controls.Add($buttonResize) $mainForm.Add_Closing({ $mainForm.Dispose() }) [void][System.Windows.Forms.Application]: :EnableVisualStyles() [void][System.Windows.Forms.Application]::Run($mainForm)

GPT4

Sorry, I see the problem. The problem is that when converting the value in the text box to an integer, there may be characters that are not allowed and the conversion fails. To get around this, we can check that the value in the textbox is a valid integer before doing the conversion. Please sendUpdateAspectRatioThe function changes to the following:

function UpdateAspectRatio { if ($checkboxMaintainAspectRatio.Checked -and $global:originalWidth.Value -gt 0 -and $global:originalHeight.Value -gt 0) { if ($textboxWidth.Focused) { if ([int32]::Width.Text,TryParse(1TP3 [ref]$null)) { $height = [int]($textboxWidth.Text) * $global:originalHeight.Value / $global:originalWidth.Value $textboxHeight.Text = [string]$height } } elseif ($textboxHeight.Focused) { if ([int32 ]::TryParse($textboxHeight.Text, [ref]$null)) { $width = [int]($textboxHeight.Text) * $global:originalWidth.Value / $global:originalHeight.Value $textboxWidth.Text = [string]$width } } } }

This should fix the conversion of the input.

Hollen9

MsgBox:

Image resized and saved as System.Management.Automation.PSReference`1[System._resized.String]

Console:

magick.exe: unable to open image 'System.Management.Automation.PSReference1[System.String]': No such file or directory @ error/blob.c/OpenBlob/3569. magick.exe: no decode delegate for this image format `'@error/constitute.c/ReadImage/746.

still fail

GPT4

Sorry, I made a mistake. we need to remove$global:inputImagePathand$outputImagePathreferences to ([ref]). Please change the following two lines to:

$global:inputImagePath = ""

and will:

$outputImagePath = [System.IO.Path]::ChangeExtension($global:inputImagePath, '_resized' + [System.IO.Path]::GetExtension($global:inputImagePath))

updated to:

$outputImagePath = [System.IO.Path]::ChangeExtension($global:inputImagePath.Value, '_resized' + [System.IO.Path]::GetExtension($global:inputImagePath.Value))

This should do the trick. Please try again to see if this works.

Hollen9

After the modification, I just dragged the picture into it, and an error occurred, which was normal:

The property 'Value' cannot be found on this object. Verify that the property exists and can be set. At C:\Program Files (Portable)\SomePowershell\ImageResize - DEV.ps1:64 char:13 + $global:inputImagePath.Value = $files[0] + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo : InvalidOperation : (:) [], RuntimeException + FullyQualifiedErrorId : PropertyAssignmentException

My current overall program looks like this:

Add-Type -AssemblyName System.Windows.Forms Add-Type -TypeDefinition @" using System; using System.Windows.Forms; public class FileDropLabel : Label { public FileDropLabel() { AllowDrop = true; DragEnter += (s, e) => { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; }; } } "@ -ReferencedAssemblies @('System.Windows.Forms.dll', 'System.Drawing.dll ') $global: originalWidth = [ref]0 $global:originalHeight = [ref]0 $global:inputImagePath = "" function UpdateAspectRatio { if ($checkboxMaintainAspectRatio. gt 0) { if ($textboxWidth.Focused) { if ([int32]::TryParse($textboxWidth.Text, [ref]$null)) { $height = [int]($textboxWidth.Text) * $global:originalHeight.Value / $global: originalWidth.Value $textboxHeight.Text = [string]$height } } elseif ($textboxHeight.Focused) { if ([int32]::TryParse($textboxHeight.Text, [ref]$null)) { $width = [int]($textboxHeight.Text) * $global:originalWidth.Value / $global:originalHeight.Value $textboxWidth.Text = [string]$width } } } } $mainForm = New-Object System.Windows.Forms.Form $mainForm.Text = 'Image Resizer' $mainForm3TPForm40 1Width = .Height = 250 $labelDropImage = New-Object FileDropLabel $labelDropImage.Text = 'Drag and drop an image here' $labelDropImage.Size = New-Object System.Drawing.Size(350, 50) $labelDropImage.Location = New-Object System.Drawing. Point(20, 20) $labelDropImage.BackColor = [System.Drawing.SystemColors]::ControlLight $labelDropImage.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter $labelDropImage.BorderStyle = [System.Windows.Forms.BorderStyle]::FixedSingle $labelDropImage.Add_DragDrop({ $files = $_.Data.GetData([Windows.Forms.DataFormats]::FileDrop) if ($files.Count -eq 1 -and [System.IO.File]::Exists($files[0]) ) { $imageExtensions = @('.jpg', '.jpeg', '.png', '.bmp', '.gif') $fileExtension = [System.IO.Path]::GetExtension($files[0]). ToLower() if ($imageExtensions -contains $fileExtension) { $originalImage = [System.Drawing.Image]::FromFile($files[0]) $global:originalWidth.Value = $originalImage.Width $global:originalHeight.TextHeightValue1TP3.ightTorigin = $global:originalWidth.Value $textboxHeight.Text = $global:originalHeight.Value $global:inputImagePath.Value = $files[0] $labelDropImage.Text = $global:inputImagePath.Value } else { [System.Windows.Forms].Message 'Unsupported image format.', 'Error', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } }) $mainForm.Controls.Add($labelDropImage) $labelWidth = New-Object System.Windows.Forms.Label $labelWidth.Text = 'Width:' $labelWidth.Location = New-Object System.Drawing.Point(20, 80) $labelWidth.Size = New-Object System.Drawing.Size(50 , 20) $mainForm.Controls.Add($labelWidth) $textboxWidth = New-Object System.Windows.Forms.TextBox $textboxWidth.Location = New-Object System.Drawing.Point(80, 80) $textboxWidth.Size = New-Object System.Drawing .Size(50, 20) # $textboxWidth.Add_Leave({ UpdateAspectRatio }) $textboxWidth.Add_TextChanged({ UpdateAspectRatio }) $mainForm.Controls.Add($textboxWidth) $labelHeight = New-ObjectHeightSystem.Windows.Forms.Label :' $labelHeight.Location = New-Object System.Drawing.Point(150, 80) $labelHeight.Size = New-Object System.Drawing.Size(50, 20) $mainForm.Controls.Add($labelHeight) $textboxHeight = New-Object System .Windows.Forms.TextBox $textboxHeight.Location = New-Object System.Drawing.Point(210, 80) $textboxHeight.Size = New-Object System.Drawing.Size(50, 20) # $textboxHeight.Add_Leave({ UpdateAspectRatio }) $textboxHeight .Add_TextChanged({ UpdateAspectRatio }) $mainForm.Controls.Add($textboxHeight) $checkboxMaintainAspectRatio = New-Object System.Windows.Forms.CheckBox $checkboxMaintainAspectRatio.Text = 'Maintain Aspect Ratio' $checkboxDrawingLock0Maintain-AspectRat2 , 110) $checkboxMaintainAspectRatio.Checked = $true $mainForm.Controls.Add($checkboxMaintainAspectRatio) $buttonResize = New-Object System.Windows.Forms.Button $buttonResize.Text = 'Resize Image' $buttonPoint.Resize.ObjectLocationSystem = New , 140) $buttonResize.Size = New-Object System.Drawing.Size(100, 30) $buttonResize.Add_Click({ if (-not [string]::IsNullOrEmpty($global:inputImagePath)) { $outputImagePath = [System.IO.Path ]::ChangeExtension($global:inputImagePath.Value, '_resized' + [System.IO.Path]::GetExtension($global:inputImagePath.Value)) $resizeCommand = "magick `"$($global:inputImagePath)`" -resize $ ($textboxWidth.Text)`x$($textboxHeight.Text) `"$($outputImagePath)`"" try { $resizeResult = Invoke-Expression -Command $resizeCommand [System.Windows.Forms.MessageBox]::Show("Image resized and saved as `n$outputImagePath", 'Success', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information) } catch { $errorMessage = $_.Exception.Message [System.Windows.Forms .MessageBox]::Show("Error occurred during resizing: `n$errorMessage", 'Error', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error) } } else { [System.Windows.Forms.MessageBox]::Show('Please drag and drop an image to be resized.', 'Error', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms .MessageBoxIcon]::Error) } }) $mainForm.Controls.Add($buttonResize) $mainForm.Add_Closing({ $mainForm.Dispose() }) [void][System.Windows.Forms.Application]::EnableVisualStyles() [void] [System.Windows.Forms.Application]::Run($mainForm)

GPT4

Sorry for the problem caused by the change just now. Now I understand what the problem is. Please put the following code:

$global:inputImagePath = ""

change to:

$global:inputImagePath = New-Object System.Management.Automation.PSReference("")

Then:

$global:inputImagePath.Value = $files[0]

updated to:

$global:inputImagePath.Value = $files[0].ToString()

This should solve the problem you're having. Please try to execute the script again.

Hollen9

MsgBox is now working.
But the key picture output still fails:
Console

magick.exe: unable to open image 'System.Management.Automation.PSReference': No such file or directory @ error/blob.c/OpenBlob/3569. magick.exe: unable to open module file 'C:\Program Files\ ImageMagick\modules\coders\IM_MOD_RL_PSREFERENCE_.dll': No such file or directory @ warning/module.c/GetMagickModulePath/677. magick.exe: no decode delegate for this image format `PSREFERENCE' @ error/constitute.c/ReadImage/ 746.

GPT4

Please put the following code:

$resizeCommand = "magick `"$($global:inputImagePath)`" -resize $($textboxWidth.Text)`x$($textboxHeight.Text) `"$($outputImagePath)`""

change to:

$resizeCommand = "magick `"$($global:inputImagePath.Value)`" -resize $($textboxWidth.Text)`x$($textboxHeight.Text) `"$($outputImagePath)`""

This should solve the problem you're having. Please try to execute the script again.

Hollen9

It worked!

GPT4

(pawn no response)

TEST

Modify .hcacess on Apache Server to allow CORS for specified domains

Motivation

I purchased a .tech domain recently, and made it a alias domain to hollen9.com.
However, some src requests are blocked due to CORS policy.
Typical symptoms are blank images, failure to load external fonts, scripts, etc. You can verify it by checking your dev console on the browser by pressing Shift+Ctrl/Command+i.

Solution

Locate your .htacess file of your website, for analog it is a config file just like web.config on IIS.
Open it with a text editor, insert the following:

# Allow loading of alias domain resources # You should modify the domains to suit your needs. SetEnvIf Origin "http(s)?://(www\.)?(holllen.tech|hollen9.com)$" AccessControlAllowOrigin=$0 Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin Header merge Vary Origin

Force reload your previous page by pressing Ctrl+F5 or Command+Shift+R, and viola! Now all images are visible!

References

TEST

Introduce: LangBranch Shortcode

View Plugin Page On WordPress.org

What is LangBranch

It's a simple plugin enable you to use a shortcode like below to display correspond language version of content based on get_locale().

[langbranch aio en_US="English version" en_GB="en_US" zh_TW="Chinese version" ja_JP="Japanese バージョン"] [langbranch en_US] Content here will only be displayed if get_locale() returns "en_US". [/langbranch ] [langbranch en_US zh_TW] Content here will only be displayed if get_locale() returns "en_US" or "zh_TW". [/langbranch]

Motivation

I've been using TranslatePress to provide multi locale experience for visiters.
However, I had been suffering from losting translated content once I updated original language's content, until I decided to create a simple shortcode to solve this problem.

Usages

AIO (1-liner) Mode

[langbranch aio en_US="English version" en_GB="en_US" zh_TW="Chinese version" ja_JP="Japanese バージョン"]

By appending aio after langbranch main tag, you can setup one specific paragraph in several languages, and if you decide that some locale user to share the same language, you can just type the locale code you want to refer to directly in content. For example, you can make UK version the same as US version.

However, if LangBranch go too deep (chain over 5 stacks) it will fail.
Don't do this:

--1---||---2---||---3---||---4---||---5---||---6-- -> Oh no!
en_US -> en_GB -> en_AU -> en_HK -> zh_TW -> ja_JP

Seperate Mode

[langbranch en_US] Content here will only be displayed if get_locale() returns "en_US". [/langbranch] [langbranch en_US zh_TW] Content here will only be displayed if get_locale() returns "en_US" or "zh_TW". , only displayed when get_locale() returns "en_US" or "zh_TW". [/langbranch]

Very straight forward, isn't?
But when using several shortcodes, I would suggest you don't put a linebreak between [/langbranch] and [langbranch], in order to prevent unwanted linebreak <br> being rendered.

Optional step

All contents enclosed by [langbranch] will be rendered enclosed by <div class="langbranch" data-no-translation=""></div>
So if you are using auto machine translating like TranslatePress offers, you may want to exclude all selector .langbranch.

Recaps

This plugin is at its early stage of developing, so you may encounter some issues while using it.
For the worst case, it breaks your site up.
If that happens, don't be panic! Just go to your wp-content/plugins directory and delete langbranch and you shall be fine.

TEST

Vantage Theme Issue: Sticky Nav doesn't work on mobile view

Solution


Just simply comment out && !isMobileDevice, and it will work like a charm!

Github solved issue: #1

However, to do this directly on a theme However, to do this directly on a theme could be changed in any future updates is probably not a good idea.

Instead, we copy that .js file to our child theme js directory.
Then, we have to dequeue the original .js by inserting the commands to your child theme's functions.php:

function vantage_child_enqueue_parent_style() { wp_dequeue_script('vantage-main'); wp_enqueue_script('vantage-main', get_stylesheet_directory_uri() . '/js/vantage-hollen-main.js', array( 'jquery' ) ) ; } add_action( 'wp_enqueue_scripts', 'vantage_child_enqueue_parent_style', 8 );

In this way, any future minor update pushed by Vantage Dev Team won't clear your modified code, as long as there won't be any structural changes, like ids's and/or classes' renaming.

Reflection

It took me almost two hours at late night debugging (3 AM), and it almost got me: I thought it was caused due to the lack of support of $(body) and scrollTop() on mobile device. Tried so many solution to no avail, then I decided to go to sleep.
and you know what, I solved it in 30 minutes after having a lunch at noon.

TEST

WordPress: Format and colorize code block by applying prism.js

Motivations

for (int i = 5; i < 10 ; i++) { Console.WriteLine("Hello Moto?"); }

If you are using Vantage for your WordPress site, and you want to make your code block looks fancy, follow the instructions:

Instructions

1. Make sure you have created a child theme based on Vantage, and it's activated.

2. Reset styles applied to code block.

I highly recommend to work with WP-SCSS plugin when writing CSS/SCSS, so you can have stylesheets organized without the costs of performance by using @import.

/* Reset the style set by Vantage (the parent theme) */ .entry-content pre, .entry-content code { background: unset; font-family: unset; border: unset; box-shadow: unset; overflow-x : unset; }

Later we will apply prism.js and its stylesheet.

3. Insert code snippits to your child theme's "functions.php"

function code_pre_theme(){ // To check if currently viewing page is a "post" if (is_singular('post')) { wp_enqueue_script('prism-js', 'https://cdn.jsdelivr.net/ npm/prismjs@1.28.0/prism.min.js'); wp_enqueue_script('prism-core-js', 'https://cdn.jsdelivr.net/npm/prismjs@1.28.0/components/prism -core.min.js'); wp_enqueue_style('prism-css', 'https://cdn.jsdelivr.net/npm/prismjs@1.28.0/themes/prism.min.css'); wp_enqueue_script( 'prism-autoloader-js', 'https://cdn.jsdelivr.net/npm/prismjs@1.28.0/plugins/autoloader/prism-autoloader.min.js'); } } add_action('wp_enqueue_scripts&#039 ;, 'code_pre_theme', 10); //Number 10 heres depend on site. The princlple is to set a number larger than the essential scripts and styles belong to your parent theme, which is vantage in this case.

By enqueuing prism-core.min.js and prism-autoloader.min.js, it will utomatically loads languages's style when necessary.
You may opt-in languages based on your needs. For example, to load certain style based on has_tag('php'), has_tag('csharp') result.
Visit prism.js at cdnjs.com for more programming language supports.

Conlusion

You don't have to follow every steps as I did, as you may come up with a better solution for your own site.

At the time I wrote this article, I absolutely have zero knowledge in PHP, only knowing C#, Javascript, Java, SCSS; writing and modifying some php script isn't complicated, so go ahead and try all the possibilities.