discord-rich-presence-plex/core/imgur.py

32 lines
1.2 KiB
Python
Raw Normal View History

from .config import config
from PIL import Image
from typing import Optional
from utils.logging import logger
import io
2022-05-14 09:43:02 +00:00
import models.imgur
import requests
2024-08-30 14:59:02 +00:00
def uploadToImgur(url: str) -> Optional[str]:
try:
originalImageBytesIO = io.BytesIO(requests.get(url).content)
originalImage = Image.open(originalImageBytesIO).convert("RGB")
newImage = Image.new("RGB", originalImage.size)
2024-08-30 14:59:02 +00:00
newImage.putdata(originalImage.getdata()) # pyright: ignore[reportArgumentType]
maxSize = config["display"]["posters"]["maxSize"]
2024-02-10 07:12:58 +00:00
if maxSize:
newImage.thumbnail((maxSize, maxSize))
newImageBytesIO = io.BytesIO()
newImage.save(newImageBytesIO, subsampling = 0, quality = 90, format = "JPEG")
2024-10-17 18:30:52 +00:00
response = requests.post(
"https://api.imgur.com/3/image",
headers = { "Authorization": f"Client-ID {config['display']['posters']['imgurClientID']}" },
files = { "image": newImageBytesIO.getvalue() }
2024-10-17 18:30:52 +00:00
)
logger.debug("HTTP %d, %s, %s", response.status_code, response.headers, response.text.strip())
data: models.imgur.UploadResponse = response.json()
if not data["success"]:
raise Exception(data["data"]["error"])
return data["data"]["link"]
except:
logger.exception("An unexpected error occured while uploading an image to Imgur")