图片文件转base64字符串

import base64
from io import BytesIO
from PIL import Image


def img_to_base64(img_file):
    img_pil = Image.open(img_file)
    
    output_buffer = BytesIO()
    img_pil.save(output_buffer, format='JPEG')
    
    img_byte_data = output_buffer.getvalue()
    img_base64_str = base64.b64encode(img_byte_data)
    
    return img_base64_str

图片base64转文件

import base64
from io import BytesIO
from PIL import Image
import re 


def base64_to_img(img_base64_str, img_file=None):
    img_base64_data = re.sub('^data:image/.+;base64,', '', img_base64_str)
    img_byte_data = base64.b64decode(img_base64_data)
    img = BytesIO(img_byte_data)
    
    img_pil = Image.open(image_data)
    if img_file:
        img_pil.save(img_file)
       
    reture img_pil

图片array转base64字符串

from PIL import Image
from io import BytesIO

def img_array_to_base64(img_array, img_format):
    img_pil = Image.fromarray(img_array)
    
    img_io = io.BytesIO()
    img_pil.save(img_io, format=img_format)
      
    return img_io.getvalue()

图片url转base64字符串

import base64
import requests


def img_url_to_base64(img_url):  
    rep = requests.get("img_url") 
    img_base64 = base64.b64encode(rep.content)
    
    return img_base64

# image decoding and without it's won't work due to some '\xff' error
#decoded_img= base64.b64decode(img_base64)

图片url转网页格式

import io
import base64
import requests


def get_image_thumbnail(image_bytes, bbox=None, size = (400,400)):
    '''
    图片写入字节流
    '''
    image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
    image.thumbnail(size, Image.ANTIALIAS)
    if isinstance(bbox, dict):
        width, height = image.size
        top = int(bbox.get('t', 0) * height)
        right = int(bbox.get('r', 1) * width)
        bottom = int(bbox.get('b', 1) * height)
        left = int(bbox.get('l', 0) * width)
        draw = ImageDraw.Draw(image)
        draw.rectangle((left, top, right, bottom), fill=None, outline="#FF0000", width=3)
    imgByteArr = io.BytesIO()
    image.save(imgByteArr, format='jpeg')
    return imgByteArr.getvalue()

#
response = requests.get("img_url") 
image_bytes = get_image_thumbnail(req.content, bbox)
image_base64 = base64.b64encode(image_bytes)

image_type = Image.open(io.BytesIO(image_bytes)).format
if isinstance(image_base64, bytes):
    url = "data:image/" + image_type + ";base64," + image_base64.decode()
elif isinstance(image_base64, str):
    url = "data:image/" + image_type + ";base64," + image_base64
else:
    url = "data:image/" + image_type + ";base64," + image_base64
Last modification:September 16th, 2022 at 08:07 pm