Convert files to and from Base64 in PowerShell without text conversion
Round-trip a PNG with ReadAllBytes and WriteAllBytes. Check the encoded length and compare SHA-256 hashes to verify the restored file.
Read the input as a byte array
A text reader can reinterpret image bytes or handle newlines while reading. Use the .NET ReadAllBytes method and pass its result to Convert.ToBase64String. The Base64 result is the first stage where this workflow needs a string.
Run the round trip in a fresh folder
Download the original sample PNG into the current folder. The example resolves its full path and writes restored.png next to it. Use a fresh directory because WriteAllBytes replaces an existing file with that name.
$src = (Resolve-Path ./sample-grid.png).Path
$dst = Join-Path (Split-Path $src) restored.png
$value = [Convert]::ToBase64String([IO.File]::ReadAllBytes($src))
[IO.File]::WriteAllBytes($dst, [Convert]::FromBase64String($value))
$value.Length
(Get-FileHash $src -Algorithm SHA256).Hash -eq (Get-FileHash $dst -Algorithm SHA256).HashCheck the length and the digest
For the 81-byte sample, the encoded length is 108 and the hash comparison returns True. If you already have a file containing Base64, read it with $value = Get-Content ./sample.b64 -Raw and use the FromBase64String and WriteAllBytes steps. Sending the restored byte array through Out-File would put it through a text output path.