TEST

Export clear text json from Aegis Authenticator and transfer it to PowertoysRunTOTP by KawaiiZapic

This article will introduce how to export and convert the plaintext JSON data in Aegis Authenticator into the format required by PowertoysRunTOTP, helping you import two-factor authentication (2FA) accounts from Aegis into the PowerToys Run TOTP expansion kit.

Warning: Do not keep plain text JSON files on your computer for long periods of time. It is recommended to store it in an encrypted storage space, such as pCloud Crypto, or use 7zip compression and set a secure password to protect the file.

Step 1: Export Aegis Authenticator plaintext JSON

First, export your 2FA account information from Aegis Authenticator. Make sure the exported file is in clear text JSON format and saved to a safe location, for example C:\path\to\aegis_export.json.

Step 2: Write a PowerShell script

Write a PowerShell script to convert the JSON file exported by Aegis into the format required by PowertoysRunTOTP. The following is the complete script. You can copy and paste it with Notepad and save it as a .ps1 file. For example convert_aegis_to_powertoysrun.ps1.

$inputFilePath = "P:\Crypto Folder\aegis.json" $outputFilePath = "$env:LOCALAPPDATA\Microsoft\PowerToys\PowerToys Run\Settings\Plugins\Community.PowerToys.Run.Plugin.TOTP\OTPList.json_new" try { # Read the Aegis JSON file and ensure it uses UTF-8 encoding $jsonContent = Get-Content -Raw -Path $inputFilePath -Encoding UTF8 # Check if the JSON file is empty if ($jsonContent -eq $null -or $jsonContent.Trim() -eq "") { throw "The Aegis JSON file is empty or contains no content" } try { # Parse the JSON file $aegisData = $jsonContent | ConvertFrom-Json } catch { throw "JSON parsing error: $_" } # Prepare the JSON structure for PowerToysRunTOTP $powerToysRunTOTP = @{ Version = 2 Entries = @() } # Check the structure of the Aegis JSON file if ($aegisData.db.entries -ne $null) { # Iterate over Aegis entries and extract necessary data foreach ($entry in $aegisData.db.entries ) { $newEntry = @{ Name = "$($entry.issuer): $($entry.name)" Key = $entry.info.secret IsEncrypted = $false } $powerToysRunTOTP.Entries += $newEntry } } else { throw "Entries in the Aegis JSON file are empty or not found" } # Write the converted data to the PowerToysRunTOTP JSON file $powerToysRunTOTP | ConvertTo-Json -Depth 3 | Set-Content -Path $outputFilePath -Encoding UTF8 Write-Host "Aegis JSON conversion successful and saved to $outputFilePath" } catch { Write-Host "An error occurred during the conversion process: $_" }

Step 3: Execute the PowerShell script

Method 1: Right-click and execute on Windows 10 or higher

  1. Make sure PowerToys is turned off. This prevents the PowertoysRun OTP expansion kit from overwriting user-edited files during execution.
  2. Open File Explorer and find the PowerShell script file you saved, for example convert_aegis_to_powertoysrun.ps1.
  3. Right-click the file and select "Run with PowerShell".
  4. If you see a Windows security warning, select "More Information" and click "Do Anyway."

Method 2: Use PowerShell command execution

  1. Make sure PowerToys is turned off. This prevents the PowertoysRun OTP expansion kit from overwriting user-edited files during execution.
  2. press Win+X key and select "Windows PowerShell (Admin)" or "Windows Terminal (Admin)".
  3. In the PowerShell window, enter the following command without pressing Enter (there is a space after -File):
    PowerShell -ExecutionPolicy Bypass -File 
  4. Open File Explorer and find the PowerShell script file you saved.
  5. Drag the file into the PowerShell window. This will automatically fill in the full path to the file.
  6. Confirm the command as shown below and press Enter to execute:
    PowerShell -ExecutionPolicy Bypass -File "C:\path\to\convert_aegis_to_powertoysrun.ps1"

Step 4: Verify import results

  1. Open PowerToys, which will automatically launch the TOTP expansion kit.
  2. After the PowertoysRun TOTP expansion kit is launched, the data in the OTPList.json file will be automatically encrypted.
  3. Open PowerToys Run and check if your 2FA account was successfully imported. If all goes well, you should be able to see the account numbers you imported and use them to authenticate.

Summarize

Through the above steps, we successfully converted and imported the plaintext JSON file exported by Aegis Authenticator into PowertoysRunTOTP. This method can help you easily manage your 2FA accounts and migrate them between different devices.
If you think the article is helpful to you, please leave a message below, press the smiley face or share it with others.

If you have any relevant suggestions, please leave a message!

TEST

WordPress Docker maintenance and deployment notes

Portainer is recommended for convenient graphical management

Docker Compose

If you are worried that the latest will be broken every time you pull and redeploy, just choose the appropriate version number yourself.

version: "4.5" services: tsumugi-db: image: mariadb:latest volumes: - tsumugi-mariadb_data:/var/lib/mysql restart: always environment: MARIADB_ROOT_PASSWORD: your-mariadb-root-pwd MARIADB_DATABASE: your-wordpress-db MARIADB_USER: yourDbUserForWp MARIADB_PASSWORD: yourMariaDbPassword tsumugi-wordpress: depends_on: - tsumugi-db #links: # - mariadb:mysql image: wordpress:latest volumes: - tsumugi-wordpress_data:/var/www/html - tsumugi-wordpress_php:/usr/local /etc/php restart: always environment: WORDPRESS_DB_HOST: tsumugi-db WORDPRESS_DB_USER: yourDbUserForWp WORDPRESS_DB_PASSWORD: yourMariaDbPassword WORDPRESS_DB_NAME: your-wordpress-db zunda-db: image: mariadb:latest volumes: - zundamon-mariadb_data:/var/lib/mys ql restart : always environment: MARIADB_ROOT_PASSWORD: some-mariadb-root-pwd MARIADB_DATABASE: zundamon-wordpress MARIADB_USER: zundamochi114514 MARIADB_PASSWORD: some-mariadb-password zundamon-wordpress: depends_on: - zunda-db image: wordpress:latest volumes: - zundamon-wordpress_data: /var/www/html - zundamon-wordpress_php:/usr/local/etc/php restart: always environment: WORDPRESS_DB_HOST: zunda-db WORDPRESS_DB_USER: zundamochi114514 WORDPRESS_DB_PASSWORD: some-mariadb-password WORDPRESS_DB_NAME: zundamon-wordpress WORDPRESS_TABLE_PREFIX: w pzundamochi_ https-portal : image: steveltn/https-portal:1 ports: - "192.168.19.19:80:80" - "192.168.19.19:443:443" restart: always environment: DOMAINS: 'www.zundamon-kawaii.com -> http ://tsumugi-wordpress:80, blog.zundamon.co.jp -> http://zundamon-wordpress:80, www.zundamon.co.jp -> http://zundamon-wordpress:80, zundamon.co .jp -> http://zundamon-wordpress:80' CLIENT_MAX_BODY_SIZE: 500M STAGE: 'production' # Don't use production until staging works # FORCE_RENEW: 'true' volumes: - https-portal-data:/var/lib /https-portal volumes: tsumugi-mariadb_data: {} tsumugi-wordpress_data: {} tsumugi-wordpress_php: {} zundamon-mariadb_data: {} zundamon-wordpress_data: {} zundamon-wordpress_php : {} https-portal-data: {}

debug

  • Browser Developer Console Printout 413 Request entity too large
    • https-portal needs to adjust environment variables 
CLIENT_MAX_BODY_SIZE: 500M

By the way, I accidentally added a semicolon after 500M to become \CLIENT\_MAX\_BODY\_SIZE: 500M;\ As a result, the container is still running, but obviously the website is not responding.
Querying the error.log of https-portal will show the following characteristic error message. My Volume configuration is located in the dd87****87b folder.

2024/07/19 13:52:01 [emerg] 59#59: unexpected ";" in /etc/nginx/nginx.conf:56
  • Unable to upload files larger than 2MB to WordPress
    • Since my Compose configuration has mapped PHP directly to Volume, I can sudo dolphin /var/lib/docker/volumes/yourstack-zundamon-wordpress_php/_data/conf.d New uploads.ini The writing content is as follows
file_uploads = On memory_limit = 500M upload_max_filesize = 500M post_max_size = 500M max_execution_time = 600

Backup Script

#!/bin/bash # Define variable NFS_SERVER="192.168.xx" # Destination Hostname NFS_PATH="/volume1/Backup-NFS" # Destination directory LOCAL_PATHS=( "/var/lib/docker/volumes/yourblog_mariadb_data/_data " "/var/lib/docker/volumes/yourblog_wordpress_data/_data" #...Add and adjust yourself, no comma is needed at the end of the string) MOUNT_POINT="/mnt/backup_nfs" DATE_NOW=$(date +'%Y%m%d%H%M%S') BACKUP_FILE="$MOUNT_POINT/web/websiteBackup_$DATE_NOW.tar.gz" # Create a mount point mkdir -p $MOUNT_POINT # Check whether NFS has mounted the mountpoint -q $MOUNT_POINT if [ $? -ne 0 ]; then echo "Mount NFS shared directory ..." mount -t nfs $NFS_SERVER:$NFS_PATH $MOUNT_POINT if [ $? -ne 0 ]; then echo "Failed to mount NFS shared directory" exit 1 fi fi # Compress and back up data tar -czf $BACKUP_FILE -C / ${LOCAL_PATHS [@]} # Delete redundant backups find $MOUNT_POINT -name "websiteBackup_*.tar.gz" -type f -print | while read FILE; do FILE_DATE=$(basename $FILE | sed 's/websiteBackup_\(.*\) \.tar\.gz/\1/') FILE_EPOCH=$(date -d "${FILE_DATE:0:8}" +%s) NOW_EPOCH=$(date +%s) AGE=$(( (NOW_EPOCH - FILE_EPOCH) / 86400 )) if [ $AGE -le 7 ]; then # retains one daily copy within 7 days continue elif [ $AGE -le 30 ]; then # retains one weekly copy within one month FILE_DAY=$(date -d "$ {FILE_DATE:0:8}" +%u) if [ $FILE_DAY -eq 1 ]; then continue fi elif [ $AGE -le 365 ]; then # retains a monthly copy of FILE_DAY=$(date -d "${ within one year FILE_DATE:0:8}" +%d) if [ $FILE_DAY -eq 1 ]; then continue fi elif [ $AGE -gt 365 ]; then # retain the first day of each year FILE_MONTH_DAY=$(date -d "${ FILE_DATE:0 :8}" +%m%d) if [ $FILE_MONTH_DAY -eq "0101" ]; then continue fi fi # Delete files that do not meet retention rules rm -f $FILE done

crontab -e with micro editor

TEST

Resolving the Black Screen Issue When Switching to Desktop Mode on Steam Deck

When you encounter a black screen while attempting to switch to desktop mode on your Steam Deck, it can be a frustrating experience. However, there's a straightforward solution that can help resolve this issue. Here's a step-by-step guide to fixing the problem :

Solution

  1. Switching Accounts:

    • Start by logging into a new Steam account through the game interface.
    • Switch to desktop mode using this new account.
    • If the switch is successful, proceed to delete all files (excluding folders) located in Home/.local/share/kscreen and Home/.local/share/kscreen/outputs.
    • For safety, instead of deleting, you may choose to cut and backup these files elsewhere before removing them from the original location.
    • After backing up, switch back to the game mode, log into the original account that was experiencing issues, and try switching to desktop mode again. The problem should now be resolved.
  2. For Users with Decky Extension Framework Installed:

    • Ensure that you have the Decky Extension Framework installed and have set up a root password beforehand.
    • Install the Decky Terminal extension.
    • Execute sudo -i to log in as root, then run the following commands:
      cd /home/deck/.local/share/kscreen rm * cd /home/deck/.local/share/kscreen/outputs rm * exit
    • After executing these commands, close the Terminal and attempt to enter desktop mode again; the issue should be fixed.
    • It's recommended to create a script file named fix.sh containing the above commands and store it in /home/deck/.Remember to make the script executable with the command sudo chmod +x /home/deck/fix.sh.

By following these steps, you should be able to overcome the black screen issue on your Steam Deck and enjoy a seamless gaming experience.


It can be frustrating when you encounter a black screen when trying to switch to desktop mode on your Steam Deck. However, there is a simple solution that can help solve this problem. Here's a step-by-step guide to troubleshooting the issue:

Solution

  1. Switch accounts:

    • First log in to a new Steam account through the game interface.
    • Switch to desktop mode using this new account.
    • If the switch is successful, then delete the Home/.local/share/kscreen and Home/.local/share/kscreen/outputs All files (excluding folders).
    • To be on the safe side, you may choose to cut and back up these archives elsewhere before deleting them from their original location.
    • After backing up, switch back to game mode, log in to the account that originally had the problem, and try switching to desktop mode again. The problem should now be resolved.
  2. For users who have installed the Decky extension framework:

    • Make sure you have installed the Decky extension framework and set the root password beforehand.
    • Install the Decky Terminal extension.
    • implement sudo -i Log in as root and execute the following command:
      cd /home/deck/.local/share/kscreen rm * cd /home/deck/.local/share/kscreen/outputs rm * exit
    • After executing these commands, close Terminal and try entering desktop mode again; the problem should be fixed.
    • It is recommended to create a file called fix.sh script file containing the above commands and stored in /home/deck/. Remember to use the command sudo chmod +x /home/deck/fix.sh Make the script executable.

By following these steps, you should be able to overcome the black screen issue on Steam Deck and enjoy a seamless gaming experience.

TEST

Windows 11 PowerShell script double-click execution method

This article will demonstrate how to enable double-click execution of PowerShell scripts (.ps1 files) on Windows 11. Follow the steps below:

1. Download and extract the SetUserFTA tool:https://kolbi.cz/SetUserFTA.zip

2. Open CMD as administrator and run the following command (for Windows PowerShell):

ftype Microsoft.PowerShellScript.1="C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -ExecutionPolicy Bypass -f "%1"

3. Use the SetUserFTA tool with the following parameters:

SetUserFTA.exe.ps1 Microsoft.PowerShellScript.1

If you prefer using PowerShell 7, replace the command in step 2 with:

ftype Microsoft.PowerShellScript.1="C:\Program Files\PowerShell\7\pwsh.exe" -NoLogo -ExecutionPolicy Bypass -f "%1"

After completing these steps, you can double-click .ps1 files to execute them on Windows 11.

References:
https://www.elevenforum.com/t/run-ps1-files-double-click-on-windows-11.2433/

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)