How to base64 encode image in linux bash / shell

前端 未结 6 1857
说谎
说谎 2021-01-29 23:30

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

相关标签:
6条回答
  • 2021-01-29 23:42

    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`
    
    0 讨论(0)
  • 2021-01-29 23:42

    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.

    0 讨论(0)
  • 2021-01-29 23:47

    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

    0 讨论(0)
  • 2021-01-29 23:49

    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")"
    
    0 讨论(0)
  • 2021-01-29 23:59

    To base64 it and put it in your clipboard:

    file="test.docx"
    base64 -w 0 $file  | xclip -selection clipboard
    
    0 讨论(0)
  • 2021-01-30 00:07

    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 )
    
    0 讨论(0)
提交回复
热议问题