Dynamically insert images into HTML file

I am trying to dynamically insert images into my HTML file, when I say dynamically it means that when the user asks him, here are 2 consistent with what I think, for both cases, the user should put the images in a specific folder before running the code.

With a switch parameter such as: generate-html -includeImages

if the switch parameter is true then convert all images to MyImagefolder and insert one by one into my output.

or

Through a parameter that takes multiple values, in which case the user must enter the image names such as generate-html -includeImages image1.gif, image2.gif

Here is the code I am using to insert a single image into my HTML file:

$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
$image = "$PSScriptRoot\img.gif"
$ImageBits = [Convert]::ToBase64String((Get-Content $image -Encoding Byte))
$ImageHTML = "<img src=data:image/png;base64,$($ImageBits) alt='My Image'/>"

      

Then I insert my variable into my command convertto-html

.

ConvertTo-Html -Body $style -PreContent "$imageHTML" | Out-File "$PSScriptRoot\report.html"

      

-1


source to share


1 answer


An array of images can be processed like this:

$images = Get-ChildItem "C:\path\to\*.gif"
$ImageHTML = $images | % {
  $ImageBits = [Convert]::ToBase64String((Get-Content $_ -Encoding Byte))
  "<img src=data:image/png;base64,$($ImageBits) alt='My Image'/>"
}

      

If you want to use a radio button -IncludeImage

and read images from a predefined folder, or skip image paths using a parameter -IncludeImage

, you need. The latter is probably a more generic approach as it makes your code independent of a specific folder, but both approaches will work.

A function using a switch parameter might look like this:



function Generate-Html {
  Param(
    [Switch]
    [bool]$IncludeImages
  )

  if ($IncludeImages) {
    $PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
    $images = Get-ChildItem "$PSScriptRoot\*.gif"
    $ImageHTML = $images | % {
      $ImageBits = [Convert]::ToBase64String((Get-Content $_ -Encoding Byte))
      "<img src=data:image/png;base64,$($ImageBits) alt='My Image'/>"
    }

    ConvertTo-Html -Body $style -PreContent $imageHTML |
      Out-File "$PSScriptRoot\report.html"
  }
}

      

while a function using an array parameter might look like:

function Generate-Html {
  Param(
    [Parameter()]
    [string[]]$IncludeImages
  )

  if ($IncludeImages) {
    $ImageHTML = $IncludeImages | % {
      $ImageBits = [Convert]::ToBase64String((Get-Content $_ -Encoding Byte))
      "<img src=data:image/png;base64,$($ImageBits) alt='My Image'/>"
    }

    ConvertTo-Html -Body $style -PreContent $imageHTML |
      Out-File "C:\path\to\report.html"
  }
}

      

+4


source







All Articles