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.jpgor
echo -n $myImgStr | base64 -d -i > image2.jpgBut in both cases I get the following error:
base64: extra operand ‘/9j/4AAQSkZJRgABAQAAAQABAAD/7QCEUGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAGgcAmcAFHNH’
Try 'base64 --help' for more information.
Any help is appreciated.
1 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.jpgIf 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.)