2023-11-02 23:35:43 -06:00
|
|
|
import random
|
|
|
|
from pathlib import Path
|
|
|
|
|
2023-11-06 18:53:12 -07:00
|
|
|
import PIL
|
2023-11-02 23:35:43 -06:00
|
|
|
from PIL import Image
|
2023-11-11 11:16:03 -07:00
|
|
|
from tqdm import tqdm
|
2023-11-02 23:35:43 -06:00
|
|
|
|
|
|
|
|
|
|
|
def random_file_width(base_path: Path):
|
|
|
|
random_tile_file = random.choice(list(base_path.glob('*')))
|
|
|
|
with Image.open(random_tile_file) as img:
|
|
|
|
return img.size[0]
|
|
|
|
|
|
|
|
|
|
|
|
def is_png(file_path):
|
|
|
|
"""
|
|
|
|
Make sure an image is a valid PNG.
|
|
|
|
Raise exeption if could not load image.
|
|
|
|
:param file_path:
|
|
|
|
:return:
|
|
|
|
"""
|
2023-11-04 20:16:37 -06:00
|
|
|
try:
|
|
|
|
img = Image.open(file_path)
|
2023-11-11 11:10:08 -07:00
|
|
|
img.verify()
|
|
|
|
return img.format == 'PNG', img.format
|
2023-11-06 18:53:12 -07:00
|
|
|
except PIL.UnidentifiedImageError as e:
|
|
|
|
# tqdm.write(str(e))
|
2023-11-11 11:10:08 -07:00
|
|
|
return False, None
|
2023-11-11 11:16:03 -07:00
|
|
|
|
|
|
|
|
2023-11-11 11:34:42 -07:00
|
|
|
def convert_to_png(file_path):
|
2023-11-11 12:06:32 -07:00
|
|
|
try:
|
|
|
|
img = Image.open(file_path)
|
|
|
|
if img.format != 'PNG':
|
|
|
|
img.save(file_path, format='PNG')
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
except Exception:
|
|
|
|
# import traceback
|
|
|
|
# traceback.print_exc()
|
|
|
|
return False
|