- Python 에서 webframework 로 작업중
- 이미지의 src 를 그대로 사용할 수가 없는 환경이 발생해서
- 이미지를 python 에서 'rb 로 읽은 후 base64 로 encoding 해서
- str 형태의 binary data 를 response 로 web browser 에 보내서 출력하게 됐다.
- Python code
- 다음은 이미지를 'rb' 모드로 read 후 base64 로 encoding 하는 부분이다.
# sim_imgs : 이미지의 url, local 에 저장되어 있어서 file 의 경로형식이다.
# ex. /data/img/315424352564.jpg
import base64
imgs = []
for img in sim_imgs:
with open(img, 'rb') as single_img:
img_b64 = base64.b64encode(single_img.read())
imgs.append(img_b64) - 위의 코드에서
- sim_imgs 는
- 로컬에 저장되어 있는 image 파일의 경로를 저장한 list 이고
- sim_imgs 에 저장된 각 image 파일들의 file path 를 이용하여 open(img, 'rb) 모드로 읽은 후에
- 읽은 image 파일 데이터를 (sigle_img.read()) base64 를 이용해서 base64 string 으로 encoding 한 후
- img_bs64 list 에 저장한다.
- 다음은 html 코드에서 위의 데이터를 표현하는 방법이다.
<img src='https://t1.daumcdn.net/cfile/tistory/212DAD4056EAEE4C07"color:#e8bf6a;">/>
- 위의 {{=img}} 부분에 하나의 이미지 데이터를 넣어주면, image file 이 보여지게된다.
- 위의 {{=img}} 부분은 webframework 인 weppy 를 사용시, parameter 로 넘겨받은 variable 을 사용하는 syntax 이다.
- 이 {{=img}} 부분에 자신이 base64 encoding 했던 string 으로 된 image file data 를 적어주기만 하면 되므로,
javascript, ajax 등을 이용해서 자신의 상황에 맞게 처리하면 된다. - 추가
- 다음은 base64 string 으로 image data 를 받아서 temp file 에 저장하는 방법이다.
tf = tempfile.NamedTemporaryFile()
with open(tf.name, 'wb') as f:
f.write(base64.b64decode(img_base64)) - 위의 코드에서
- img_base64 가 image file 의 data 를 base64 로 encoding 한 정보를 가지고 있는 variable 이다
- 이를 base64.b64decode() 로 다시 decode 해서 temp 로 만든 tf 파일에 저장하는 형식이다.
- 만약 temp 파일이 아니라 특정 이름의 파일에 저장하고 싶다면 tf.name 부분에 저장하고 싶은 파일을 적어주면 된다.
'Python > Examples' 카테고리의 다른 글
| Python | Examples | PYTHONPATH 추가하기 (0) | 2016.03.08 |
|---|---|
| Python | Examples | Math functions (buillt-in), 버림, 반올림, 내림, 올림 (0) | 2016.03.07 |
| Python | Examples | Python code 에서 bash 명령 실행, command 실행 (0) | 2016.03.03 |
| Python | Examples | dictionary 에서 key 값만 얻기 (0) | 2016.03.02 |
| Python | Examples | BeautifulSoup | convert NavigableString to string (0) | 2016.03.02 |