Skip to content

Commit

Permalink
Make sure that image can be opened
Browse files Browse the repository at this point in the history
Checking for file extension does not ensure that the image file can be
actually opened. Check if it can be loaded into a pixbuf, and convert it if
necessary.
  • Loading branch information
City-busz committed Nov 2, 2024
1 parent 31c2a1d commit fa86a25
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
21 changes: 16 additions & 5 deletions cartridges/store/managers/cover_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@
# SPDX-License-Identifier: GPL-3.0-or-later

from pathlib import Path
from typing import NamedTuple
from typing import NamedTuple, Optional

import requests
from gi.repository import GdkPixbuf, Gio
from gi.repository import GdkPixbuf, Gio, GLib
from requests.exceptions import HTTPError, SSLError

from cartridges import shared
Expand Down Expand Up @@ -128,9 +128,20 @@ def composite_cover(
"""

# Load source image
source = GdkPixbuf.Pixbuf.new_from_file(
str(convert_cover(image_path, resize=False))
)
try:
source = GdkPixbuf.Pixbuf.new_from_file(
str(image_path)
)
except GLib.Error:
new_path = convert_cover(image_path, resize=False)

if new_path:
source = GdkPixbuf.Pixbuf.new_from_file(
str(new_path)
)
else:
return None

source_size = ImageSize(source.get_width(), source.get_height())
cover_size = ImageSize._make(shared.image_size)

Expand Down
8 changes: 0 additions & 8 deletions cartridges/utils/save_cover.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,6 @@ def convert_cover(
if not cover_path and not pixbuf:
return None

pixbuf_extensions = set()
for pixbuf_format in GdkPixbuf.Pixbuf.get_formats():
for pixbuf_extension in pixbuf_format.get_extensions():
pixbuf_extensions.add(pixbuf_extension)

if not resize and cover_path and cover_path.suffix.lower()[1:] in pixbuf_extensions:
return cover_path

try:
with Image.open(cover_path) as image:
if getattr(image, "is_animated", False):
Expand Down

0 comments on commit fa86a25

Please sign in to comment.