Created
December 25, 2024 03:38
-
-
Save SylvanG/bd94ad2c027a36a0fb2ac84d3086269c to your computer and use it in GitHub Desktop.
Extract thumbnails from broken images (images that cannot be downloaded but can be viewed from Quicklook)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# This script is to extract existing thumbnail from a picture | |
# file. (rather than create a new thumbnail) | |
from collections.abc import Iterable | |
from pathlib import Path | |
import subprocess | |
def get_image_files(dir: Path) -> Iterable[Path]: | |
image_extensions = { | |
".jpg", | |
".jpeg", | |
".png", | |
".gif", | |
".bmp", | |
".tiff", | |
".webp", | |
".heic", | |
} | |
return ( | |
file | |
for file in dir.rglob("*") | |
if file.suffix.lower() in image_extensions and file.is_file() | |
) | |
def extract_thumbnail(file: Path, output_dir: Path) -> tuple[bool, str]: | |
command = [ | |
"qlmanage", | |
"-t", | |
"-x", | |
"-s", | |
"3000", # unit: pixel. it will generate the maximum size if this value bigger than the size it has | |
"-o", | |
output_dir.as_posix(), | |
file.as_posix(), | |
] | |
result = subprocess.run( | |
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True | |
) | |
if result.returncode == 0: | |
if "produced one thumbnail" in result.stdout: | |
extracted = True | |
elif "No thumbnail created" in result.stdout: | |
extracted = False | |
else: | |
raise Exception(f"Unknown command output: {result.stdout}") | |
return extracted, result.stdout | |
raise Exception(f"Error code {result.returncode} with message {result.stderr}") | |
if __name__ == "__main__": | |
imgs = get_image_files(Path.cwd()) | |
# print(list(imgs)) | |
output = Path.home() / "Downloads" / "thumbnails" | |
fail_to_extract: list[tuple[Path, str]] = [] | |
for img in imgs: | |
print(f"Extract thumbnail for {img.name}") | |
extracted, result = extract_thumbnail(img, output_dir=output) | |
if not extracted: | |
fail_to_extract.append((img, result)) | |
print(f"Result is {result}") | |
print() | |
print(f"Following are fail to extract, total: {len(fail_to_extract)}") | |
for img, result in fail_to_extract: | |
print(img.as_posix()) | |
print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment