ExportedFunctions/Out-BarcodeImage.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<#
.SYNOPSIS
    Creates a barcode and saves it as an image file.

.DESCRIPTION
    Uses the ZXing.Net library to create barcodes and save them as image files.

.PARAMETER Content
    The contents of the barcode. This needs to be valid content for the BarcodeFormat you are writing.

.PARAMETER BarcodeFormat
    One of the barcode formats supported by ZXing.Net

.PARAMETER Options
    Barcode encoding options.

.PARAMETER Path
    The output file to create.

.PARAMETER ImageFormat
    One of the image formats supported by System.Drawing.Imaging

.PARAMETER Width
    The width in pixels of the image file.

.PARAMETER Height
    The height in pixels of the image file.

.PARAMETER Passthrough
    Indicates that the output path should be passed along in the pipeline.

.EXAMPLE
    Out-BarcodeImage -Content "test string" -Path $pwd\barcode.png

    Creates a QR code and saves it as a PNG file into the local directory.
#>

function Out-BarcodeImage {
    param(
        [Parameter(Mandatory=$true)]
        $Content,

        [ZXing.BarcodeFormat]$BarcodeFormat = [ZXing.BarcodeFormat]::QR_Code,

        [ZXing.Common.EncodingOptions]$Options,

        [String]$Path,

        [System.Drawing.Imaging.ImageFormat]$ImageFormat = [System.Drawing.Imaging.ImageFormat]::Png,

        [int]$Width,

        [int]$Height,

        [switch]$Passthrough
    )
    $Writer = New-Object ZXing.BarcodeWriterPixelData -Property @{ Format = $BarcodeFormat; Options = $Options }
    if($Width) {
        $Writer.Options.Width = $Width
    }
    if($Height) {
        $Writer.Options.Height = $Height
    }
    try {
        $PixelData = $Writer.Write($Content)

        $Height = $PixelData.Height
        $Width = $PixelData.Width
        $PixelCount = $Height * $Width

        $Bitmap = New-Object System.Drawing.Bitmap($Width, $Height)

        for($i = 0; $i -lt $PixelCount; $i++) {
            $A = $PixelData.Pixels[$i * 4 + 3] -bxor 0xff
            $R = $PixelData.Pixels[$i * 4 + 2]
            $G = $PixelData.Pixels[$i * 4 + 1]
            $B = $PixelData.Pixels[$i * 4]

            $X = $i % $Width
            $Y = [Math]::Floor( ($i / $Height) )
            try {
            $Bitmap.SetPixel($X, $Y, [System.Drawing.Color]::FromARGB($A, $R, $G, $B))
            } catch { write-host "$x $y" }
        }

        $Bitmap.Save($Path, $ImageFormat)
        if($Passthrough) {
            $Path
        }
    } catch {
        Write-Error -Message "Error creating barcode: $($_.Exception.Message)" -Exception $_.Exception
    } finally {
        if($Bitmap) {
            $Bitmap.Dispose()
        }
    }
}
Export-ModuleMember -Function Out-BarcodeImage