- restapi를 통해 이미지를 넘길경우 base64형식으로 넘겨주는 경우가 있는데 그럴경우 사용
1. imgfile to base64
file_name = '/home/data/hjhan03/cmimm/data_img_real/cjmall/fff4899a9c3ad7bdfcbabf76b0c4c3a1.jpg'
encoded_string = ''
with open(file_name, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
2. base64 to arr
import base64
import skimage
import math
import cv2
import numpy as np
from io import BytesIO
from PIL import Image
def decode(base64_str):
starter = base64_str.find(',')
image_data = base64_str[starter+1:]
image_data = bytes(image_data, encoding="ascii")
image = Image.open(BytesIO(base64.b64decode(image_data)))
return np.array(image.convert('RGB'))
def encode(image):
with BytesIO() as output_bytes:
PIL_image = Image.fromarray(skimage.img_as_ubyte(image))
PIL_image.save(output_bytes, 'JPEG')
bytes_data = output_bytes.getvalue()
base64_str = str(base64.b64encode(bytes_data), 'utf-8')
return base64_str