4

I can convert a jpeg to a base64 string using the following PowerShell command

[Convert]::ToBase64String((Get-Content -Path .\Capture.jpg -Encoding Byte)) >> capture.txt

I tried converting it back using the following

[Convert]::FromBase64String((Get-Content -Path .\capture.txt)) >> capture2.jpg

But I get a list of numbers and not a binary file. How do I convert the base64 file back to binary?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
user3213700
  • 159
  • 1
  • 2
  • 9
  • 2
    Possible duplicate of [Write bytes to a file natively in PowerShell](https://stackoverflow.com/questions/31855705/write-bytes-to-a-file-natively-in-powershell). Be sure to check the highest voted answer. – Jeroen Mostert May 03 '19 at 11:33
  • Appending with `>>` will by default output in UTF16LE encoding, so b64 quadruples the file size and UTF16LE again doubles. Better pipe to `Set-Content` or `Out-File` with encoding parameter. –  May 03 '19 at 12:34
  • Please elaborate on the background of your question: If it concerns just a binary file, I agree that this is a duplicate (and you might actually just copy the file using [`Copy-Item`](https://learn.microsoft.com/powershell/module/microsoft.powershell.management/copy-item?view=powershell-6)). What Is the is reason you trying to use `Code64` and why do you explicitly mention `JPG` in the title of your question? – iRon May 03 '19 at 12:44
  • @Jeroen Mostert that solved my problem – user3213700 May 04 '19 at 09:16

1 Answers1

2

If you want to handle it as a image you might want to rebuild it in memory (use it or make modifications) and then save it, like:

$Base64 = Get-Content -Raw -Path .\capture.txt
$Image = [Drawing.Bitmap]::FromStream([IO.MemoryStream][Convert]::FromBase64String($Base64))
$Image.Save("<path>\Image2.jpg")
iRon
  • 20,463
  • 10
  • 53
  • 79