base64encode linux,How to base64 encode image in linux bash / shell

问题

I'm trying to base64 encode an image in a shell script and put it into variable:

test="$(printf DSC_0251.JPG | base64)"

echo $test

RFNDXzAyNTEuSlBH

I've also tried something like this:

test=\`echo -ne DSC_0251.JPG | base64\`

but still with no success.

I want to do something like this:

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

I found this http://www.zzzxo.com/q/answers-bash-base64-encode-script-not-encoding-right-12290484.html

but still have had no success.

回答1:

You need to use cat to get the contents of the file named 'DSC_0251.JPG', rather than the filename itself.

test="$(cat DSC_0251.JPG | base64)"

However, base64 can read from the file itself:

test=$( base64 DSC_0251.JPG )

回答2:

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)"

Get you readable data back:

base64 -d DSC_0251.base64 > DSC_0251.JPG

See: http://www.greywyvern.com/code/php/binary2base64

回答3:

There is a Linux command for that: base64

base64 DSC_0251.JPG >DSC_0251.b64

To assign result to variable use

test=`base64 DSC_0251.JPG`

回答4:

Base 64 for html:

file="DSC_0251.JPG"

type=$(identify -format "%m" "$file" | tr '[A-Z]' '[a-z]')

echo "data:image/$type;base64,$(base64 -w 0 "$file")"

回答5:

To base64 it and put it in your clipboard:

file="test.docx"

base64 -w 0 $file | xclip -selection clipboard

回答6:

If you need input from termial, try this

lc=`echo -n "xxx_${yyy}_iOS" | base64`

-n option will not input "\n" character to base64 command.

来源:https://stackoverflow.com/questions/16918602/how-to-base64-encode-image-in-linux-bash-shell

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值