Ubuntu – How to decode an image string using base64 in command line

batchcommand line

Say I have an image image1.jpg
I can encode it using base64 tool :

myImgStr=$(base64 image1.jpg)

I tried to decode it using the following command:

base64 -i -d $myImgStr > image2.jpg

or

echo -n $myImgStr | base64 -d -i > image2.jpg

But in both cases I get the following error:

base64: extra operand ‘/9j/4AAQSkZJRgABAQAAAQABAAD/7QCEUGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAGgcAmcAFHNH’
Try 'base64 --help' for more information.

Any help is appreciated.

Best Answer

The utility base64 reads its input either from a file whose name is supplied as an argument, or from standard input. It never reads its input from a command line argument. In your case, to decode a string stored in a variable, you should supply the string on the standard input of base64.

If you are using Bash, you may use a here-string:

base64 -d <<< "$myImgStr" > image2.jpg

If your shell does not accept here-strings, you can always use:

echo "$myImgStr" | base64 -d > image2.jpg

(Note the doublequotes around "$myImgStr". You should always doublequote variable expansions unless you have a good reason not to.)