Reputation: 21468
I have a problem with the following code I am trying to run. Basically I have a single source PNG, that I want to copy over all other found PNGs within my current directory, but at the resolution of the original PNG:
# Source image to replace all found images with
$sourcePng = [System.Drawing.Image]::FromFile( 'C:\Path\To\image.png' )
# Get all .png files in the directory
Get-ChildItem *.png -Recurse | Foreach-Object {
Write-Host "Converting $_ to image.png..."
$png = New-Object System.Drawing.Bitmap( $_.ToString() )
# Make sure the target size matches the existing image
$newSize = New-Object System.Drawing.Size( $png.Width, $png.Height )
# Dispose to ensure file handles are closed
$png.Dispose()
# Create new bitmap object from source png with old image resolution and save
$newPng = New-Object System.Drawing.Bitmap( $sourcePng, $newSize )
$newPng.Save( $_.ToString(), [System.Drawing.Imaging.ImageFormat]::Png ) # Errors out here
}
However, this yields the following error:
Foreach-Object: Exception calling "Save" with "2" argument(s): "A generic error occurred in GDI+."
At line:1 char:55
+ Get-ChildItem *.png -Recurse | Foreach-Object {
+ ~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [ForEach-Object], MethodInvocationException
+ FullyQualifiedErrorId : ExternalException,Microsoft.PowerShell.Commands.ForEachObjectCommand
My initial research tells me this happens because the target file has an open handle, but calling the Dispose
function doesn't seem to open it back up again. I've checked and there are no other handles to the file I can see.
Upvotes: 0
Views: 800
Reputation: 21468
I figured out the solution after I wrote this up as I tried a couple more things, and figured this might still spare someone else the headache. Turns out, since my initial code never disposed of the $png
object, the image was still "locked" as far as GDI+ was concerned. I closed out my PowerShell session, opened a new one, and re-ran my code and the images wrote as expected.
Upvotes: 0