2023-11-04 18:13:42 +00:00
|
|
|
from .config import config
|
2023-11-05 06:13:52 +00:00
|
|
|
from PIL import Image
|
2022-05-12 07:14:23 +00:00
|
|
|
from typing import Optional
|
|
|
|
from utils.logging import logger
|
2023-11-05 06:13:52 +00:00
|
|
|
import io
|
2022-05-14 09:43:02 +00:00
|
|
|
import models.imgur
|
2022-05-12 07:14:23 +00:00
|
|
|
import requests
|
|
|
|
|
2023-11-04 18:13:42 +00:00
|
|
|
def uploadToImgur(url: str) -> Optional[str]:
|
2022-05-12 07:14:23 +00:00
|
|
|
try:
|
2023-11-05 06:13:52 +00:00
|
|
|
originalImageBytesIO = io.BytesIO(requests.get(url).content)
|
|
|
|
originalImage = Image.open(originalImageBytesIO)
|
|
|
|
newImage = Image.new("RGB", originalImage.size)
|
|
|
|
newImage.putdata(originalImage.getdata()) # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
|
|
|
|
newImageBytesIO = io.BytesIO()
|
|
|
|
newImage.save(newImageBytesIO, subsampling = 0, quality = 90, format = "JPEG")
|
2022-05-14 09:43:02 +00:00
|
|
|
data: models.imgur.UploadResponse = requests.post(
|
2022-05-12 07:14:23 +00:00
|
|
|
"https://api.imgur.com/3/image",
|
|
|
|
headers = { "Authorization": f"Client-ID {config['display']['posters']['imgurClientID']}" },
|
2023-11-05 06:13:52 +00:00
|
|
|
files = { "image": newImageBytesIO.getvalue() }
|
2022-05-12 07:14:23 +00:00
|
|
|
).json()
|
|
|
|
if not data["success"]:
|
|
|
|
raise Exception(data["data"]["error"])
|
|
|
|
return data["data"]["link"]
|
|
|
|
except:
|
2023-11-04 18:13:42 +00:00
|
|
|
logger.exception("An unexpected error occured while uploading an image to Imgur")
|