wmts-exfiltrator/pkg/image.py

43 lines
967 B
Python

import random
from pathlib import Path
import PIL
from PIL import Image
from tqdm import tqdm
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:
"""
try:
img = Image.open(file_path)
img.verify()
return img.format == 'PNG', img.format
except PIL.UnidentifiedImageError as e:
# tqdm.write(str(e))
return False, None
def convert_to_png(file_path):
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