1+ <# #############################################################################
2+ Part of PowerShell module : GenXdev.AI.ComfyUI
3+ Original cmdlet filename : ConvertComfyImageFormat.ps1
4+ Original author : René Vaessen / GenXdev
5+ Version : 1.264.2025
6+ ################################################################################
7+ MIT License
8+
9+ Copyright 2021-2025 GenXdev
10+
11+ Permission is hereby granted, free of charge, to any person obtaining a copy
12+ of this software and associated documentation files (the "Software"), to deal
13+ in the Software without restriction, including without limitation the rights
14+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15+ copies of the Software, and to permit persons to whom the Software is
16+ furnished to do so, subject to the following conditions:
17+
18+ The above copyright notice and this permission notice shall be included in all
19+ copies or substantial portions of the Software.
20+
21+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27+ SOFTWARE.
28+ ################################################################################>
29+ # ###############################################################################
30+ # ##############################################################################
31+
32+ <#
33+ . SYNOPSIS
34+ Converts image file format while preserving maximum quality.
35+
36+ . DESCRIPTION
37+ Loads an image file using System.Drawing and saves it in a different format
38+ with optimized quality settings. The function supports all major image formats
39+ including JPEG, PNG, BMP, TIFF, and GIF with special handling for JPEG quality
40+ optimization to maintain visual fidelity during conversion.
41+
42+ The function automatically determines the target format from the provided format
43+ parameter and applies appropriate encoding settings. For JPEG output, it uses
44+ 95% quality to balance file size with visual quality. For other formats, it
45+ uses lossless conversion where possible.
46+
47+ This function is particularly useful in ComfyUI workflows where generated images
48+ need to be converted to specific formats based on user requirements or
49+ compatibility needs.
50+
51+ . PARAMETER ImagePath
52+ Path to the input image file to convert. Must be a valid image file that
53+ System.Drawing can load (JPEG, PNG, BMP, TIFF, GIF, etc.). The file will
54+ be validated for existence and readability.
55+
56+ . PARAMETER OutputPath
57+ Path where the converted image should be saved. The directory will be created
58+ if it doesn't exist. If the file already exists, it will be overwritten.
59+
60+ . PARAMETER Format
61+ Target image format as a string (e.g., "Jpeg", "Png", "Bmp", "Tiff", "Gif").
62+ Case-insensitive. For JPEG format, high-quality encoding parameters are
63+ automatically applied.
64+
65+ . EXAMPLE
66+ $convertedPath = ConvertComfyImageFormat -ImagePath "input.png" `
67+ -OutputPath "output.jpg" -Format "Jpeg"
68+ Converts a PNG image to high-quality JPEG format.
69+
70+ . EXAMPLE
71+ ConvertComfyImageFormat "image.bmp" "image.png" "Png"
72+ Convert BMP to PNG using positional parameters.
73+
74+ . EXAMPLE
75+ $result = ConvertComfyImageFormat -ImagePath "source.tiff" `
76+ -OutputPath "result.gif" -Format "Gif"
77+ Convert TIFF to GIF format with quality preservation.
78+
79+ . NOTES
80+ This function requires System.Drawing to be available in the PowerShell session.
81+ The function handles resource disposal properly to prevent memory leaks and
82+ provides detailed progress feedback during conversion operations.
83+
84+ For JPEG output, the function uses 95% quality encoding to maintain visual
85+ fidelity while achieving reasonable file sizes. Other formats use their
86+ default quality settings optimized for the format characteristics.
87+ #>
88+ function ConvertComfyImageFormat {
89+
90+ [CmdletBinding ()]
91+
92+ param (
93+ # ##############################################################################
94+ [Parameter (
95+ Mandatory = $true ,
96+ Position = 0 ,
97+ HelpMessage = " Path to the input image file to convert"
98+ )]
99+ [string ]$ImagePath ,
100+ # ##############################################################################
101+ [Parameter (
102+ Mandatory = $true ,
103+ Position = 1 ,
104+ HelpMessage = " Path where the converted image should be saved"
105+ )]
106+ [string ]$OutputPath ,
107+ # ##############################################################################
108+ [Parameter (
109+ Mandatory = $true ,
110+ Position = 2 ,
111+ HelpMessage = " Target image format (Jpeg, Png, Bmp, Tiff, etc.)"
112+ )]
113+ [ValidateSet (" Jpeg" , " Jpg" , " Png" , " Bmp" , " Tiff" , " Gif" )]
114+ [string ]$Format
115+ )
116+
117+ begin {
118+
119+ # display progress for image format conversion operation
120+ Microsoft.PowerShell.Utility\Write-Progress `
121+ - Activity " ComfyUI Generation" `
122+ - Status " Converting image format to ${Format} "
123+
124+ # initialize image object variable for proper resource disposal
125+ $image = $null
126+ }
127+
128+ process {
129+
130+ try {
131+
132+ # load image using system.drawing for high-quality format conversion
133+ $image = [System.Drawing.Image ]::FromFile($ImagePath )
134+
135+ # determine target image format based on format parameter
136+ $imageFormat = switch ($Format.ToLower ()) {
137+ " jpeg" { [System.Drawing.Imaging.ImageFormat ]::Jpeg }
138+ " jpg" { [System.Drawing.Imaging.ImageFormat ]::Jpeg }
139+ " png" { [System.Drawing.Imaging.ImageFormat ]::Png }
140+ " bmp" { [System.Drawing.Imaging.ImageFormat ]::Bmp }
141+ " tiff" { [System.Drawing.Imaging.ImageFormat ]::Tiff }
142+ " gif" { [System.Drawing.Imaging.ImageFormat ]::Gif }
143+ default { [System.Drawing.Imaging.ImageFormat ]::Jpeg }
144+ }
145+
146+ # apply format-specific encoding with quality optimization
147+ if ($imageFormat -eq [System.Drawing.Imaging.ImageFormat ]::Jpeg) {
148+
149+ # configure jpeg encoder parameters for high-quality output
150+ $encoder = [System.Drawing.Imaging.Encoder ]::Quality
151+
152+ # create encoder parameters object with single quality parameter
153+ $encoderParameters = Microsoft.PowerShell.Utility\New-Object `
154+ System.Drawing.Imaging.EncoderParameters(1 )
155+
156+ # set quality parameter to 95% for high-quality jpeg output
157+ $encoderParameters.Param [0 ] = Microsoft.PowerShell.Utility\New-Object `
158+ System.Drawing.Imaging.EncoderParameter($encoder , 95L )
159+
160+ # get jpeg codec information for encoding
161+ $jpegCodec = [System.Drawing.Imaging.ImageCodecInfo ]::GetImageEncoders() |
162+ Microsoft.PowerShell.Core\Where-Object {
163+ $_.FormatID -eq [System.Drawing.Imaging.ImageFormat ]::Jpeg.Guid
164+ }
165+
166+ # save image with high-quality jpeg encoding settings
167+ $image.Save ($OutputPath , $jpegCodec , $encoderParameters )
168+ } else {
169+
170+ # save in other formats with their optimal default quality settings
171+ $image.Save ($OutputPath , $imageFormat )
172+ }
173+
174+ # clean up image object to free memory resources immediately
175+ $image.Dispose ()
176+
177+ # get file information for size reporting and validation
178+ $fileInfo = Microsoft.PowerShell.Management\Get-Item - LiteralPath $OutputPath
179+
180+ # calculate file size in megabytes for user-friendly feedback
181+ $fileSizeMB = [Math ]::Round($fileInfo.Length / 1 MB , 2 )
182+
183+ Microsoft.PowerShell.Utility\Write-Verbose (" Converted to ${Format} : " +
184+ " ${fileSizeMB} MB" )
185+
186+ # return the output path for pipeline continuation
187+ return $OutputPath
188+ }
189+ catch {
190+
191+ # handle conversion errors gracefully with informative warnings
192+ Microsoft.PowerShell.Utility\Write-Warning " Failed to convert image format: $_ "
193+
194+ # ensure image object is disposed even on error to prevent memory leaks
195+ if ($image ) { $image.Dispose () }
196+
197+ # return original path when conversion fails
198+ return $ImagePath
199+ }
200+ }
201+
202+ end {
203+ }
204+ }
205+ # ###############################################################################
0 commit comments