import io from PIL import Image def to_bytes(image: Image.Image) -> bytes: with io.BytesIO() as output: image.save(output, format="JPEG") return output.getvalue() def resize_image_to512(image: Image.Image) -> Image.Image: iw, ih = image.size if iw > ih: image = image.resize((512, int(512 * ih / iw))) else: image = image.resize((int(512 * iw / ih), 512)) return image def from_bytes(data: bytes) -> Image.Image: return Image.open(io.BytesIO(data)) def padd_image(image: Image.Image, to_width: int, to_height: int) -> Image.Image: iw, ih = image.size value = min(to_width, to_height) # resize Image if iw > ih: image = image.resize((value, int(value * ih / iw))) else: image = image.resize((int(value * iw / ih), value)) # padd Image iw, ih = image.size img = Image.new("RGBA", (to_width, to_height), (0, 0, 0, 0)) img.paste(image, ((to_width - iw) // 2, (to_height - ih) // 2)) return img