Skip to main content

Creates an in memory (or Base64 encoded) representation of a QR code.

<#
.SYNOPSIS
    Creates an in memory (or Base64 encoded) representation of a QR code.

.DESCRIPTION
    A spin-off of the QRCodeGenerator.New-QRCodeText cmdlet, that instead writes the QR code to an array of bytes,
    or as a Base64 encoded string.

    This function clones the API for New-PSOneQRCodeText.ps1, with the exception of -Show and -OutPath:
    https://github.com/TobiasPSP/Modules.QRCodeGenerator/blob/master/QRCodeGenerator/2.6.0/New-PSOneQRCodeText.ps1.

.NOTES
    Requires the [QRCodeGenerator](https://www.powershellgallery.com/packages/QRCodeGenerator/) module.
#>
function New-QRCodeTextToBytes
{
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Should never return 1 byte')]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Following QRCodeGenerator''s existing API')]
    [CmdletBinding()]
    [OutputType([System.Byte[]])]
    [OutputType([System.String])]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Text,

        [Parameter()]
        [ValidateRange(10, 2000)]
        [int]
        $Width = 100,

        [Parameter()]
        [byte[]]
        $DarkColorRgba = @(0, 0, 0),

        [Parameter()]
        [byte[]]
        $LightColorRgba = @(255, 255, 255),

        [Parameter()]
        [switch]
        $Base64Encode
    )

    $payload = "$Text"

    $generator = New-Object -TypeName QRCoder.QRCodeGenerator
    $data = $generator.CreateQrCode($payload, 'Q')
    $code = New-Object -TypeName QRCoder.PngByteQRCode -ArgumentList ($data)
    $byteArray = $code.GetGraphic($Width, $DarkColorRgba, $LightColorRgba)

    if ($Base64Encode)
    {
        [System.Convert]::ToBase64String($byteArray)
    }
    else
    {
        $byteArray
    }
}