python base64 string image example

 본 블로그에서 c 언어로 base64의 원리를 설명하고, 인코더/디코더를 구현해 포스팅한 적이 있다.

base64 인코딩 디코딩 예제 c 소스

python에서는 base64 관련 모듈을 제공하고 있어, 손쉽게 사용할 수 있다.

import base64

base64 모듈은 base16, base32, base64, base85 데이터 인코딩/디코딩을 모두 지원하고 있다.

https://docs.python.org/3.7/library/base64.html


python base64 string encode/decode 

base64 모듈의 base64 데이터 인코딩/디코딩 API는 아래와 같다.

import base64
base64.b64encode(s, altchars=None)
base64.b64decode(s, altchars=None, validate=False)
base64.standard_b64encode(s)
base64.standard_b64decode(s)
base64.urlsafe_b64encode(s)
base64.urlsafe_b64decode(s)


사용법은 아래 예제 코드와 같이 함수 아규먼트로 문자열의 bytes-like object를 넣어, 함수를 호출하면 된다.

import base64

print('b64encode/b64decode') 
code = base64.b64encode(b'https://ryanclaire.blogspot.com')
print('base64 :',code)
decoded =base64.b64decode(code)
print('str :',decoded)

print('standard_b64encode/standard_b64decode') 
code = base64.standard_b64encode(b'https://ryanclaire.blogspot.com')
print('base64 :',code)
decoded = base64.standard_b64decode(code)
print('str :',decoded)

print('urlsafe_b64encode/urlsafe_b64decode') 
code = base64.urlsafe_b64encode(b'https://ryanclaire.blogspot.com')
print('base64 :',code)
decoded =base64.urlsafe_b64decode(code)
print('str :',decoded)

코드 실행 결과는 아래와 같다.

bytes-like object는 앞에 'b'를 붙이며, 문자열과 bytes-like object은 아래와 같이 간단히 변환 가능하다.

'string'.encode() -> b'bytes_like object'
b'bytes-like object'.decode() ->'string'


python base64 image encode/decode 

python base64 모듈에는 파일을 읽어 base64 데이터로 변환하는 API도 제공한다.

import base64
base64.decode(input, output)
base64.encode(input, output)

아규먼트 input, output은 모두 파일 오브젝트이다.  입력을 bytes-like object이기 때문에 파일 open시 바이너리로 읽고/쓰도록, 파일 모드에 'b'를 추가해야 한다.

아래는 위 API를 사용해 이미지 파일은 base64 데이터로 만들고, 다시 base64 데이터를 사용해 이미지로 복원하는 예제 코드이다.

import base64
import os

if os.path.isfile('STSCI-H-p1715a-f-140x140.png') is True:
    in_f = open('STSCI-H-p1715a-f-140x140.png','rb')
    out_f = open('base64.encode','wb')
    base64.encode(in_f,out_f)
    in_f.close()
    out_f.close()

    in_f = open('base64.encode','rb')
    out_f = open('base64.decode.png','wb')
    base64.decode(in_f,out_f)
    in_f.close()
    out_f.close()


테스트에 사용된 원본 이미지는 다음과 같다.

인코딩된 base64 데이터의 일부는 다음과 같다.

위 데이터를 사용해 다시 복원한 이미지는 아래와 같다.


댓글

이 블로그의 인기 게시물

바로 프로젝트 적용 가능한 FIR Filter (low/high/band pass filter )를 c나 python으로 만들기

간단한 cfar 알고리즘에 대해

쉽게 설명한 파티클 필터(particle filter) 동작 원리와 예제

windows에서 간단하게 크롬캐스트(Chromecast)를 통해 윈도우 화면 미러링 방법

mkfs.fat Device or resource busy 에러 해결법