From 67840eae8cfddc991e442f83b15050b7a92d8f79 Mon Sep 17 00:00:00 2001 From: codezjx Date: Sat, 21 Oct 2017 16:28:55 +0800 Subject: [PATCH] #20 Bugfix: Resize the cover image (max allow: 640x640, same as 163), thus can reduce the file size. --- ncm/downloader.py | 4 ++++ ncm/file_util.py | 13 +++++++++++++ requirements.txt | 1 + setup.py | 1 + 4 files changed, 19 insertions(+) diff --git a/ncm/downloader.py b/ncm/downloader.py index 7385a3e..2e58ce0 100644 --- a/ncm/downloader.py +++ b/ncm/downloader.py @@ -7,6 +7,7 @@ import requests from ncm import config from ncm.api import CloudApi from ncm.file_util import add_metadata_to_song +from ncm.file_util import resize_img def download_song_by_id(song_id, download_folder, sub_folder=True): @@ -59,6 +60,9 @@ def download_song_by_song(song, download_folder, sub_folder=True): cover_file_name = 'cover_{}.jpg'.format(song_id) download_file(cover_url, cover_file_name, song_download_folder) + # resize cover + resize_img(os.path.join(song_download_folder, cover_file_name)) + # add metadata for song song_file_path = os.path.join(song_download_folder, song_file_name) cover_file_path = os.path.join(song_download_folder, cover_file_name) diff --git a/ncm/file_util.py b/ncm/file_util.py index d32283a..4d647b1 100644 --- a/ncm/file_util.py +++ b/ncm/file_util.py @@ -2,6 +2,19 @@ from mutagen.mp3 import MP3, HeaderNotFoundError from mutagen.id3 import ID3, APIC, TPE1, TIT2, TALB, error +from PIL import Image + + +def resize_img(file_path, max_size=(640, 640), quality=90): + try: + img = Image.open(file_path) + except IOError: + print('Can\'t open image:', file_path) + return + + if img.size[0] > max_size[0] or img.size[1] > max_size[1]: + img.thumbnail(max_size, Image.ANTIALIAS) + img.save(file_path, quality=quality) def add_metadata_to_song(file_path, cover_path, song): diff --git a/requirements.txt b/requirements.txt index 98fdb5f..ddc65e3 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ requests>=2.17.3 pycrypto>=2.6.1 mutagen>=1.38.0 +Pillow>=4.3.0 \ No newline at end of file diff --git a/setup.py b/setup.py index caa06cc..6eb33c7 100644 --- a/setup.py +++ b/setup.py @@ -9,6 +9,7 @@ setup( 'requests>=2.17.3', 'pycrypto>=2.6.1', 'mutagen>=1.38.0', + 'Pillow>=4.3.0', ], entry_points={