Skip to content

Instantly share code, notes, and snippets.

@Tokariew
Last active February 19, 2020 18:47
Show Gist options
  • Save Tokariew/db47133157e76e76532c5164399c2e13 to your computer and use it in GitHub Desktop.
Save Tokariew/db47133157e76e76532c5164399c2e13 to your computer and use it in GitHub Desktop.
resize album arts in flac files
import argparse
from concurrent.futures import ProcessPoolExecutor
from io import BytesIO
from pathlib import Path
from imageio import imread, imwrite
from skimage.transform import resize
from mutagen.flac import FLAC, Picture
def resize_art(*args):
args = args[0]
i = args[0]
file = args[1]
b = FLAC(file)
ehh = []
try:
for i, pic in enumerate(b.pictures):
stream, type, shape, channels = resize_pic(pic)
img = make_img(stream, type, shape, channels)
ehh.append(img)
b.clear_pictures()
for img in ehh:
b.add_picture(img)
b.save()
except IndexError:
print(file.name)
return i
def get_shape(shape):
x, y = shape
if x > y:
new_x = 512
scale = x / new_x
new_y = 2 * round(y / scale / 2)
else:
new_y = 512
scale = y / new_y
new_x = 2 * round(x / scale / 2)
return new_x, new_y
def make_img(stream, type, shape, channels=3):
img = Picture()
img.data = stream.getvalue()
img.mime = u"image/jpeg"
img.type = type
img.width = shape[0]
img.height = shape[1]
img.depth = 8 * channels
return img
def resize_pic(pic):
data = imread(pic.data)
type = pic.type
stream = BytesIO()
if data.shape[0] > 512 or data.shape[1] > 512:
shape = get_shape(data.shape[:2])
data = (255 * resize(data, shape)).astype('uint8')
else:
shape = data.shape[:2]
if data.ndim == 2:
imwrite(stream, data[:, :], 'jpg')
channels = 1
else:
imwrite(stream, data[:, :, :3], 'jpg')
channels = 3
return stream, type, shape, channels
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Reduce size of album arts in flac files')
parser.add_argument(
'filepath',
metavar='path',
type=str,
help='path to folder containing flacs to reduce album art')
path_user = Path(parser.parse_args().filepath)
flacs = [flac for flac in Path('.').glob('**/*.flac')]
total_tracks = len(flacs)
with ProcessPoolExecutor() as executor:
for track in executor.map(resize_art, enumerate(flacs)):
pass
# print(f'{track}/{total_tracks}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment