2013-06-04 14 views
51

Sto cercando di base64 codificare un'immagine in uno script di shell e la mettono in variabile:Come BASE64 immagine codificare in linux bash/shell

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

Ho anche provato qualcosa di simile:

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

ma ancora senza successo.

voglio fare qualcosa di simile:

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 

Ho trovato questo http://www.zzzxo.com/q/answers-bash-base64-encode-script-not-encoding-right-12290484.html

ma ancora non hanno avuto successo.

risposta

73

è necessario utilizzare cat per ottenere i contenuti del file denominato 'DSC_0251 .JPG ', piuttosto che il nome del file stesso.

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

Tuttavia, base64 può leggere dal file stesso:

test=$(base64 DSC_0251.JPG) 
+0

con il gatto funziona, grazie mille amico. So che può leggere dal file, ma ha ancora problemi a memorizzarlo nella variabile così test = "$ (cat DSC_0251.JPG | base64)" funziona per me. – dash00

+1

Quali problemi? I due comandi sopra dovrebbero produrre risultati identici, tranne il primo è un [uso inutile di cat] (http://partmaps.org/era/unix/award.html). – chepner

+0

hai ragione. Questo è quello che dovrei fare '$ RESPONSE =" $ (curl -v -X POST -d '{"image": \ 'base64 | $ DIR $ IMAGE \", "location": $ LOCATION, "time_created": $ TIMECREATED} '-H' Tipo di contenuto: text/plain; charset = UTF8 '--max-time 180 -s $ URL) ";' – dash00

29

C'è un comando di Linux per questo: base64

base64 DSC_0251.JPG >DSC_0251.b64 

Per assegnare risultato per uso variabile

test=`base64 DSC_0251.JPG` 
+7

'base64 -d DSC_0251.b64> DSC_0251.JPG' può restituire dati leggibili. – Stallman

22

unico risultato linea:

base64 -w 0 DSC_0251.JPG 

Per HTML:

echo "data:image/jpeg;base64,$(base64 -w 0 DSC_0251.JPG)" 

file AS:

base64 -w 0 DSC_0251.JPG > DSC_0251.JPG.base64 

In variabile:

IMAGE_BASE64="$(base64 -w 0 DSC_0251.JPG)" 

Nel variabile per HTML:

IMAGE_BASE64="data:image/jpeg;base64,$(base64 -w 0 DSC_0251.JPG)" 

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

0

Base 64 per HTML:

file="DSC_0251.JPG" 
type=$(identify -format "%m" "$file" | tr '[A-Z]' '[a-z]') 
echo "data:image/$type;base64,$(base64 -w 0 "$file")" 
Problemi correlati