[英]How to base64 encode image in linux bash / shell
我正在尝试在 shell 脚本中对图像进行 base64 编码并将其放入变量中:
test="$(printf DSC_0251.JPG | base64)"
echo $test
RFNDXzAyNTEuSlBH
我也尝试过这样的事情:
test=\`echo -ne DSC_0251.JPG | base64\`
但仍然没有成功。
我想做这样的事情:
curl -v -X POST -d '{"image":$IMAGE_BASE64,"location":$LOCATION,"time_created":$TIMECREATED}' -H 'Content-type: text/plain; charset=UTF8' http://192.168.1.1/upload
我发现这个http://www.zzzxo.com/q/answers-bash-base64-encode-script-not-encoding-right-12290484.html
但仍然没有成功。
您需要使用cat
来获取名为“DSC_0251.JPG”的文件的内容,而不是文件名本身。
test="$(cat DSC_0251.JPG | base64)"
但是, base64
可以从文件本身读取:
test=$( base64 DSC_0251.JPG )
单行结果:
base64 -w 0 DSC_0251.JPG
对于HTML
:
echo "data:image/jpeg;base64,$(base64 -w 0 DSC_0251.JPG)"
作为文件:
base64 -w 0 DSC_0251.JPG > DSC_0251.JPG.base64
在变量中:
IMAGE_BASE64="$(base64 -w 0 DSC_0251.JPG)"
在HTML
变量中:
IMAGE_BASE64="data:image/jpeg;base64,$(base64 -w 0 DSC_0251.JPG)"
在OSX上, base64
二进制不同,参数也不同。 如果你想在OSX上使用它,你应该删除-w 0
。
单行结果:
base64 DSC_0251.JPG
对于HTML
:
echo "data:image/jpeg;base64,$(base64 DSC_0251.JPG)"
作为文件:
base64 DSC_0251.JPG > DSC_0251.JPG.base64
在变量中:
IMAGE_BASE64="$(base64 DSC_0251.JPG)"
在HTML
变量中:
IMAGE_BASE64="data:image/jpeg;base64,$(base64 DSC_0251.JPG)"
@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.JPG
cat DSC_0251.JPG | @base64
创建具有以下内容的base64.sh
文件:
#!/usr/bin/env bash
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
使其可执行:
chmod a+x base64.sh
用法:
./base64.sh DSC_0251.JPG
cat DSC_0251.JPG | ./base64.sh
让您恢复可读数据:
base64 -d DSC_0251.base64 > DSC_0251.JPG
如果您需要终端输入,试试这个
lc=`echo -n "xxx_${yyy}_iOS" | base64`
-n
选项不会在 base64 命令中输入“\n”字符。
用于 html 的 Base 64:
file="DSC_0251.JPG"
type=$(identify -format "%m" "$file" | tr '[A-Z]' '[a-z]')
echo "data:image/$type;base64,$(base64 -w 0 "$file")"
对其进行base64并将其放入剪贴板:
file="test.docx"
base64 -w 0 $file | xclip -selection clipboard
使用echo
时请务必小心(这里有很多答案),因为它会在末尾添加一个换行符,由于这些不祥的额外编码字符而扭曲您的编码字符串(导致例如不正确的密码): Cg==
添加在编码字符串的结尾:
例如,如果我们要编码这个字符串:
$ MINIO_SECRET_KEY=VsarGnNADHGv
使用 `printf' 它看起来像这样(正确):
$ AWS_SECRET_ACCESS_KEY="$(printf $MINIO_SECRET_KEY | base64)" && echo $AWS_SECRET_ACCESS_KEY
VnNhckduTkFESEd2
...但是像这样的echo
(不正确):
$ AWS_SECRET_ACCESS_KEY="$(echo $MINIO_SECRET_KEY | base64)" && echo $AWS_SECRET_ACCESS_KEY
VnNhckduTkFESEd2Cg==
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.