Skip to content

Instantly share code, notes, and snippets.

@addohm
Created December 10, 2018 03:07
Show Gist options
  • Save addohm/2ec443eeaae8c115767251795caf3914 to your computer and use it in GitHub Desktop.
Save addohm/2ec443eeaae8c115767251795caf3914 to your computer and use it in GitHub Desktop.
Proportional Image Constraints
Sub ConstrainImage(filePath as String)
Dim img As Image = Image.FromFile(filePath)
Dim imgX As Integer = img.Width
Dim imgXLim As Integer = 350
Dim imgY As Integer = img.Height
Dim imgYLim As Integer = 100
Dim imgXdiff As Integer = imgX - imgXLim
Dim imgYdiff As Integer = imgY - imgYLim
Dim growFactor As Double
Dim shrinkFactor As Double
.PageSetup.DifferentFirstPageHeaderFooter = 0
With .Sections(1).Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Shapes
'Check to see if the image is too big
If imgX > imgXLim Or imgY > imgYLim Then
If imgXdiff > imgYdiff Then
shrinkFactor = (imgXLim / imgX) - ((imgXLim / imgX) Mod 0.1) 'Decimal Floor
ElseIf imgYdiff > imgXdiff Then
shrinkFactor = (imgYLim / imgY) - ((imgYLim / imgY) Mod 0.1) 'Decimal Floor
End If
imgX = imgX * shrinkFactor
imgY = imgY * shrinkFactor
'If the image isn't too big, check to see if it's too small
ElseIf imgX < imgXLim Or imgY < imgYLim Then
If imgXdiff > imgYdiff Then
growFactor = (imgXLim / imgX) - ((imgXLim Mod imgX) / imgX) 'Floor
ElseIf imgYdiff > imgXdiff Then
growFactor = (imgYLim / imgY) - ((imgYLim Mod imgY) / imgY) 'Floor
End If
imgX = imgX * growFactor
imgY = imgY * growFactor
End If
With .AddPicture(filePath)
.Width = imgX
.Height = imgY
End With
End With
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment