-
Notifications
You must be signed in to change notification settings - Fork 104
/
Convert-ImageToHtml.ps1
73 lines (60 loc) · 2.5 KB
/
Convert-ImageToHtml.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
function Convert-ImageToHtml
{
<#
.SYNOPSIS
This function can be used to convert an image file into an HTML IMG tag with an image
embedded in the SRC so that an external image file doesn't have to be referenced.
.PARAMETER $ImageFile
The image file path.
.PARAMETER $MakeHtml
An HTML file will be created using the same name as the image file.
.EXAMPLE
Convert a single image file to an HTML IMG tag and display the code.
PS C:\> Convert-ImageToHtml -$ImageFile c:\temp\picture.png -Verbose
.EXAMPLE
Convert a directory of images to HTML IMG tags and display the code.
PS C:\> Get-ChildItem *.png | select fullname | Convert-ImageToHtml -Verbose
.EXAMPLE
Convert a directory of images to HTML IMG tags, display the code, and write them to html files.
PS C:\> Get-ChildItem *.png | select fullname | Convert-ImageToHtml -Verbose -MakeHtml
.NOTES
Author: Scott Sutherland (@_nullbind)
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'The image file path.')]
[string]$ImageFile,
[Parameter(Mandatory = $false,
HelpMessage = 'An HTML file will be created using the same name as the image file.')]
[switch]$MakeHtml
)
Process {
try {
# Process for common parameter names if pipeline is used
if($PSCmdlet.MyInvocation.ExpectingInput){
$CheckFullName = $_ | gm | where name -like "fullname"
if($CheckFullName){
$ImageFile = $_.fullname
}
}
# Verbose info
Write-Verbose "Processing $ImageFile"
# Read image file
$ImageBytes = [System.IO.File]::ReadAllBytes("$ImageFile")
# Convert to base64 string
$ImageString = [System.Convert]::ToBase64String($ImageBytes)
# Create HTML with an embedded image
$output = "<img src=`"data:image/png;base64, $ImageString`" />"
# Display image tag
$output
if($MakeHtml){
$output | Out-File "$ImageFile.html"
}
}catch{
Write-Error "Something went wrong. Check your paths. :)" -ErrorId B1 -TargetObject $_
}
}
}