Saturday, April 26, 2014

PowerShell function to Update an Image or create a new image from an existing one

#This function can be used to change the color of an image or to cut out a part of an image.
#This can be used to clear pictures up for OCR'ing.
#Here are some example calls

# This example changes any pixel with more than 170 parts of blue to white.
#Update-ImageColor -CurrentFileName "c:\pic.jpg" -NewFileName "c:\PicNoBlue.jpg" -MaxBlue 170 -newColor $([System.Drawing.Color]::White)
#This function displays color in each pixel to help define the above statements parameters. 
#http://programmingthisandthat.blogspot.ca/2014/04/powershell-function-to-display-rgb.html 

# This example changes any pixel with more than 170 parts of blue to white.

#Update-ImageColor -CurrentFileName "c:\pic.jpg" -NewFileName "c:\small.jpg" -WidthStartPosition 100 -Width 100 -height 100 -heighttartPosition 100

Function Update-ImageColor{
[CmdletBinding()]
Param( [Parameter(Mandatory=$True,Position=1)] [string]$CurrentFileName,
[Parameter(Mandatory=$True,Position=1)] [string]$NewFileName,
[System.Drawing.Color]$newColor = [System.Drawing.Color]::Black,
[int]$MinCombined = -1,
[int]$MaxCombined = 800,
[int]$MaxRed = 400,
[int]$MaxGreen = 400,
[int]$MaxBlue = 400,
[int]$MinRed = -1,
[int]$MinGreen = -1,
[int]$MinBlue = -1,
[int]$Width=0,
[int]$height=0,
[int]$WidthStartPosition=0,
[int]$heighttartPosition=0,
[int]$ZoomFactor=1)
try {
$scrBitmap = [System.Drawing.Bitmap]($CurrentFileName)
$ActualColor = New-Object System.Drawing.Color
#make an empty bitmap the same size as scrBitmap
if($Width -eq 0){$Width = $scrBitmap.Width}
if($height -eq 0){$height = $scrBitmap.Height}
$newBitmap = new-object System.Drawing.Bitmap $Width, $height
for ($i = 0; $i -lt $newBitmap.Width; $i++) {
for ($j = 0; $j -lt $newBitmap.Height; $j++) {
#get the pixel from the scrBitmap image
$actulaColor = $scrBitmap.GetPixel($i+$WidthStartPosition, $j+$heighttartPosition);
if(($actulaColor.R -gt $MaxRed -or $actulaColor.R -lt $MinRed) -or
($actulaColor.G -gt $MaxGreen -or $actulaColor.G -lt $MinGreen) -or
($actulaColor.B -gt $MaxBlue -or $actulaColor.B -lt $MinBlue) -or
($actulaColor.R + $actulaColor.G + $actulaColor.B) -lt $MinCombined -or
($actulaColor.R + $actulaColor.G + $actulaColor.B) -gt $MaxCombined){

     $newBitmap.SetPixel($i, $j, $newColor)
}
else {

$newBitmap.SetPixel($i, $j, $actulaColor)
}

}

}
Remove-Item $NewFileName -Force -ErrorAction SilentlyContinue
#Size newSize = new Size((int)(originalBitmap.Width * zoomFactor), (int)(originalBitmap.Height * zoomFactor));
#Bitmap bmp = new Bitmap(originalBitmap, newSize);
$newBitmap.Save($NewFileName,[System.Drawing.Imaging.ImageFormat]::Jpeg)
$newBitmap.Dispose()
$scrBitmap.Dispose()
return "$NewFileName : Conversion Complete."


}
catch [Net.WebException] {
return $_.Exception

}

}

No comments:

Post a Comment