How to base64 encode image in linux bash / shell
Encode
On Linux
Single line result:
base64 -w 0 DSC_0251.JPG
For HTML
:
echo "data:image/jpeg;base64,$(base64 -w 0 DSC_0251.JPG)"
As file:
base64 -w 0 DSC_0251.JPG > DSC_0251.JPG.base64
In variable:
IMAGE_BASE64="$(base64 -w 0 DSC_0251.JPG)"
In variable for HTML
:
IMAGE_BASE64="data:image/jpeg;base64,$(base64 -w 0 DSC_0251.JPG)"
On OSX
On OSX, the base64
binary is different, and the parameters are different. If you want to use it on OSX, you should remove -w 0
.
Single line result:
base64 DSC_0251.JPG
For HTML
:
echo "data:image/jpeg;base64,$(base64 DSC_0251.JPG)"
As file:
base64 DSC_0251.JPG > DSC_0251.JPG.base64
In variable:
IMAGE_BASE64="$(base64 DSC_0251.JPG)"
In variable for HTML
:
IMAGE_BASE64="data:image/jpeg;base64,$(base64 DSC_0251.JPG)"
Generic OSX/Linux
As Shell Function
@base64() { if [[ "${OSTYPE}" = darwin* ]]; then # OSX if [ -t 0 ]; then base64 "$@" else cat /dev/stdin | base64 "$@" fi else # Linux if [ -t 0 ]; then base64 -w 0 "$@" else cat /dev/stdin | base64 -w 0 "$@" fi fi}# Usage@base64 DSC_0251.JPGcat DSC_0251.JPG | @base64
As Shell Script
Create base64.sh
file with following content:
#!/usr/bin/env bashif [[ "${OSTYPE}" = darwin* ]]; then # OSX if [ -t 0 ]; then base64 "$@" else cat /dev/stdin | base64 "$@" fielse # Linux if [ -t 0 ]; then base64 -w 0 "$@" else cat /dev/stdin | base64 -w 0 "$@" fifi
Make it executable:
chmod a+x base64.sh
Usage:
./base64.sh DSC_0251.JPGcat DSC_0251.JPG | ./base64.sh
Decode
Get you readable data back:
base64 -d DSC_0251.base64 > DSC_0251.JPG