PoshCode Archive  Artifact [50658a16eb]

Artifact 50658a16ebfcee07702c601cfc08212f6b5f693a6f0ad5aa4a883ab1401ed78a:

  • File Compress-Bitmap.ps1 — part of check-in [3e9183d4f0] at 2018-06-10 12:56:48 on branch trunk — Compress a bitmap to a certain filesize, using the PSCX Import-Bitmap, Resize-Bitmap, and Export-Bitmap … and a little trial and error. (user: Joel Bennett size: 1670)

# encoding: ascii
# api: powershell
# title: Compress-Bitmap
# description: Compress a bitmap to a certain filesize, using the PSCX Import-Bitmap, Resize-Bitmap, and Export-Bitmap … and a little trial and error.
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# function: Compress-Bitmap
# x-poshcode-id: 1290
# x-archived: 2013-05-22T18:29:49
# x-published: 2010-08-24T14:48:00
#
#
function Compress-Bitmap {
PARAM(
   [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
   [IO.FileInfo]$SourceFile
,
   [Parameter(Mandatory=$true, Position=1)]
   [String]$DestinationFile
,   
   [Parameter(Mandatory=$false)]
   [Int]$Width
,  [Parameter(Mandatory=$false)]
   [Int]$Height   
,  [Parameter(Mandatory=$false)]
   [Int]$MaxFilesize
,  [Parameter(Mandatory=$false)]
   [Int]$Quality = 100
)
BEGIN { if($SourceFile) { $SourceFile = Get-ChildItem $SourceFile } }
PROCESS {
   # Work our way down until we get a small enough file (this might be slow)
   [string]$intermediate = [IO.path]::GetRandomFileName() + ".jpeg"
   $bitmap = Import-Bitmap $SourceFile
   
   if($Width -and $Height) {
      $bitmap = Resize-Bitmap -Bitmap $bitmap -Width $Width -Height $Height
   } else { # work around another bug in Export-Bitmap
      $bitmap = Resize-Bitmap -Bitmap $bitmap -Percent 100
   }
   
   do { 
      Export-Bitmap -Bitmap $bitmap -Path $intermediate -Quality ($Quality--)
   } while( $MaxFilesize -and ((Get-ChildItem $intermediate).Length -gt $MaxFilesize))
   Write-Host "Output Quality: $($Quality + 1)%" -Foreground Yellow
   Move-Item $intermediate $DestinationFile -Force -Passthru
}
}