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)