🐛 Fix photo invalid dimensions

This commit is contained in:
omg-xtao 2023-09-21 15:42:14 +08:00 committed by GitHub
parent bc76f6297b
commit ff66b29240
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 6 deletions

View File

@ -108,10 +108,11 @@ class Hyperion:
self.download_image(post_info.post_id, post_info.image_urls[page], page)
for page in range(len(post_info.image_urls))
]
result_list = await asyncio.gather(*task_list)
for result in result_list:
if isinstance(result, ArtworkImage):
art_list.append(result)
result_lists = await asyncio.gather(*task_list)
for result_list in result_lists:
for result in result_list:
if isinstance(result, ArtworkImage):
art_list.append(result)
def take_page(elem: ArtworkImage):
return elem.page
@ -119,7 +120,7 @@ class Hyperion:
art_list.sort(key=take_page)
return art_list
async def download_image(self, art_id: int, url: str, page: int = 0) -> ArtworkImage:
async def download_image(self, art_id: int, url: str, page: int = 0) -> List[ArtworkImage]:
filename = os.path.basename(url)
_, file_extension = os.path.splitext(filename)
is_image = bool(file_extension in ".jpg" or file_extension in ".png")
@ -127,7 +128,7 @@ class Hyperion:
response = await self.client.get(
url, params=self.get_images_params(resize=2000) if is_image else None, de_json=False
)
return ArtworkImage(
return ArtworkImage.gen(
art_id=art_id, page=page, file_name=filename, file_extension=url.split(".")[-1], data=response.content
)

View File

@ -25,6 +25,32 @@ class ArtworkImage(BaseModel):
pass
return None
@staticmethod
def gen(*args, **kwargs) -> List["ArtworkImage"]:
data = [ArtworkImage(*args, **kwargs)]
if data[0].file_extension and data[0].file_extension in ["gif", "mp4"]:
return data
try:
with BytesIO(data[0].data) as stream, Image.open(stream) as image:
width, height = image.size
crop_height = height
crop_num = 1
max_height = 10000 - width
while crop_height > max_height:
crop_num += 1
crop_height = height / crop_num
new_data = []
for i in range(crop_num):
slice_image = image.crop((0, crop_height * i, width, crop_height * (i + 1)))
bio = BytesIO()
slice_image.save(bio, "png")
kwargs["data"] = bio.getvalue()
kwargs["file_extension"] = "png"
new_data.append(ArtworkImage(*args, **kwargs))
return new_data
except UnidentifiedImageError:
return data
class PostInfo(BaseModel):
_data: dict = PrivateAttr()