PoshCode Logo PowerShell Code Repository

Compress-Bitmap (modification of post by view diff)
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/1290"></script>download | new post

Compress a bitmap to a certain filesize, using the PSCX Import-Bitmap, Resize-Bitmap, and Export-Bitmap … and a little trial and error.

  1. function Compress-Bitmap {
  2. PARAM(
  3.    [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
  4.    [IO.FileInfo]$SourceFile
  5. ,
  6.    [Parameter(Mandatory=$true, Position=1)]
  7.    [String]$DestinationFile
  8. ,  
  9.    [Parameter(Mandatory=$false)]
  10.    [Int]$Width
  11. ,  [Parameter(Mandatory=$false)]
  12.    [Int]$Height  
  13. ,  [Parameter(Mandatory=$false)]
  14.    [Int]$MaxFilesize
  15. ,  [Parameter(Mandatory=$false)]
  16.    [Int]$Quality = 100
  17. )
  18. BEGIN { if($SourceFile) { $SourceFile = Get-ChildItem $SourceFile } }
  19. PROCESS {
  20.    # Work our way down until we get a small enough file (this might be slow)
  21.    [string]$intermediate = [IO.path]::GetRandomFileName() + ".jpeg"
  22.    $bitmap = Import-Bitmap $SourceFile
  23.    
  24.    if($Width -and $Height) {
  25.       $bitmap = Resize-Bitmap -Bitmap $bitmap -Width $Width -Height $Height
  26.    } else { # work around another bug in Export-Bitmap
  27.       $bitmap = Resize-Bitmap -Bitmap $bitmap -Percent 100
  28.    }
  29.    
  30.    do {
  31.       Export-Bitmap -Bitmap $bitmap -Path $intermediate -Quality ($Quality--)
  32.    } while( $MaxFilesize -and ((Get-ChildItem $intermediate).Length -gt $MaxFilesize))
  33.    Write-Host "Output Quality: $($Quality + 1)%" -Foreground Yellow
  34.    Move-Item $intermediate $DestinationFile -Force -Passthru
  35. }
  36. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me