Resizing a jpeg ready to upload into AD

I run an ARS  scheduled task daily to upload any new pictures into AD.  The pictures are not always in the correct format, see my earlier post to convert them to jpegs, and they are often too large to store in AD.  Don’t forget these pictures are part of the user object so will take up space in the AD database and they will be replicated to all of your DCs.  They also need to be downloaded from AD by Outlook etc. so these pictures have to be less than 10K in size.  If yo utry to load anything bigger into AD then AD will refuse the update.

Here’s a function I use to shrink the pictures – most of this code was borrowed from other scripts and I just customised it with additional error handling

The script takes 5 parameters some already have defaults, like the newLongSize which is the default for the picture long side and the temp file name suffix is set to _Resize_Temp
You call the function and provide it with the jpeg name and path to the file and a log file so you can record a log of events and the function will shrink the original file, if needed.:

Function Shrink-Jpeg {
	param (
		[string]$jpegFileName,
		[string]$jpegFilePath,
		[int]$newLongSize = 96,
		[string]$tempSuffix = "_Resize_Temp",
		[string]$logfile
	)
	[reflection.assembly]::LoadWithPartialName("System.Drawing") | Out-Null
	$sizeLimit=$newLongSize          # required size of picture's long side
	$error.clear()
	$jpegFullName = "$jpegFilePath\$jpegFileName"
	if ($originalPicture) {Remove-Variable -Name originalPicture -ErrorAction SilentlyContinue | Out-Null}
	try { $originalPicture = get-item $jpegFullName } catch{}
	try { $OldBitmap = new-object System.Drawing.Bitmap $originalPicture.FullName }
	catch {
		if ($error.count -ne 0) {	                                 # error handling
   $error | out-file $logfile -append -encoding default
   $error[($error.count-1)].TargetObject | out-file $logfile -append -encoding default
   $error.clear()
  }
	}	
	$LongSide=$OldBitmap.Width                                # locating long side of picture
	if ($OldBitmap.Width -lt $OldBitmap.Height) { 
		$LongSide=$OldBitmap.Height 
	}
	if ($LongSide -gt $SizeLimit) {                           # if long side is greater than our limit, process jpg
  if ($OldBitmap.Width -lt $OldBitmap.Height) {         # calculate dimensions of picture resize to
		 $newH=$SizeLimit
			$newW=[int]($OldBitmap.Width*$SizeLimit/$OldBitmap.Height)
		} 
		else	{
   $newW=$SizeLimit
   $newH=[int]($OldBitmap.Height*$newW/$OldBitmap.Width)
  }
  $NewBitmap = new-object System.Drawing.Bitmap $newW,$newH # create new bitmap
  $graphicObject=[System.Drawing.Graphics]::FromImage($NewBitmap)
  $graphicObject.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic # use high quality resize algorythm
  $graphicObject.DrawImage($OldBitmap, 0, 0, $newW, $newH)              # resize our picture
  $name=$jpegFilePath+"\"+$originalPicture.Basename+$tempSuffix+$originalPicture.extension                 # generating name for new picture
  Try {$NewBitmap.Save($name, ([system.drawing.imaging.imageformat]::jpeg)) | Out-Null } Catch{}  # save newly created resized jpg
		if ($NewBitmap) { if ($NewBitmap -is [IDisposable]) {try {$NewBitmap.Dispose() | Out-Null } catch{}}; Remove-Variable -Name NewBitmap -ErrorAction SilentlyContinue | Out-Null }
		if ($OldBitmap) { if ($OldBitmap -is [IDisposable]) {try {$OldBitmap.Dispose() | Out-Null } catch{}}; Remove-Variable -Name OldBitmap -ErrorAction SilentlyContinue | Out-Null }
		if ($newJpeg) { if ($newJpeg -is [IDisposable]) {try {$newJpeg.Dispose() | Out-Null } catch{}}; Remove-Variable -Name newJpeg -ErrorAction SilentlyContinue | Out-Null }
		try { $newJpeg = get-item $name } catch{}
  if ($newJpeg.length -ge $originalPicture.length)		{								                            # if resized jpg has greater size than original
			if ($newJpeg.Exists)	{
    try { $newJpeg.Delete() | Out-Null } Catch{}                                           # delete it
   }
  } 
		else	{                                                  # if resized jpg is smaller than original
			if ($newJpeg.Exists -and $originalPicture.Exists) {
   	$name=$jpegFullName
   	Try { $originalPicture.Delete() | Out-Null } catch {}                                           # delete original
   	Try { $newJpeg.MoveTo($name) | Out-Null } catch {}                                      # rename new file to original name (replace old file with new)
   }
			else {
				if ($newJpeg.Exists)	{
     $name=$jpegFullName
     Try { $newJpeg.MoveTo($name) | Out-Null } Catch {}                                      # rename new file to original name
    }
			}
  }
 } 
}#end Resize-Jpeg

Next up how to load this into AD….

Advertisements

One thought on “Resizing a jpeg ready to upload into AD

  1. […] previous posts on this topic explained how to convert the format to a  jpeg  then resize it to fit into the AD size limit and then finally how to upload it into AD in the […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.