img to base64 and base64 to arr

5298 ワード

  • restapiで画像を転送する場合、base 64フォーマットが通常使用され、そうであれば
  • が使用される.

    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