BiliBili_YouTubers_Live_Tra.../defs/thumbnail.py
2022-03-25 00:08:26 +08:00

58 lines
1.8 KiB
Python

import os
from io import BytesIO
from ci import client
from PIL import (
Image,
ImageDraw,
ImageFont,
)
def changeImageSize(maxWidth, maxHeight, image):
if image.size[0] == image.size[1]:
# Does not change the scale of the orientation image and displays it centered.
# It may look even better
newImage = image.resize((maxHeight, maxHeight))
img = Image.new("RGBA", (maxWidth, maxHeight))
img.paste(newImage, (int((maxWidth - maxHeight) / 2), 0))
return img
else:
widthRatio = maxWidth / image.size[0]
heightRatio = maxHeight / image.size[1]
newWidth = int(widthRatio * image.size[0])
newHeight = int(heightRatio * image.size[1])
newImage = image.resize((newWidth, newHeight))
return newImage
async def thumb(thumbnail, title, ctitle):
resp = await client.get(thumbnail)
if resp.status_code == 200:
image1 = Image.open(BytesIO(resp.content))
else:
return None
image2 = Image.open(f"source{os.sep}LightGreen.png")
image3 = changeImageSize(1280, 720, image1)
image4 = changeImageSize(1280, 720, image2)
image5 = image3.convert("RGBA")
image6 = image4.convert("RGBA")
Image.alpha_composite(image5, image6).save(f"data{os.sep}temp.png")
img = Image.open(f"data{os.sep}temp.png")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(f"source{os.sep}SourceHanSansCN-Regular-2.otf", 50)
font2 = ImageFont.truetype(f"source{os.sep}SourceHanSansCN-Medium-2.otf", 72)
draw.text(
(25, 615),
f"{title[:20]}...",
fill="black",
font=font2,
)
draw.text(
(27, 543),
f"{ctitle[:12]} 正在直播",
fill="black",
font=font,
)
img.save(f"data{os.sep}final.png")
return f"data{os.sep}final.png"