codezjx / netease-cloud-music-dl

Netease cloud music song downloader, with full ID3 metadata, eg: front cover image, artist name, album name, song title and so on.
MIT License
494 stars 81 forks source link

调整图片大小 的函数问题,某些歌曲会有bug,OSError: cannot write mode P as JPEG #45

Closed MountainColdWay closed 4 years ago

MountainColdWay commented 5 years ago

error:

Traceback (most recent call last):
  File "/usr/lib/python3.7/site-packages/PIL/JpegImagePlugin.py", line 628, in _save
    rawmode = RAWMODE[im.mode]
KeyError: 'P'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/bin/ncm", line 11, in <module>
    load_entry_point('netease-cloud-music-dl==0.2.0', 'console_scripts', 'ncm')()
  File "/usr/lib/python3.7/site-packages/ncm/start.py", line 67, in main
    download_song_by_id(get_parse_id(args.song_id), config.DOWNLOAD_DIR)
  File "/usr/lib/python3.7/site-packages/ncm/downloader.py", line 17, in download_song_by_id
    download_song_by_song(song, download_folder, sub_folder)
  File "/usr/lib/python3.7/site-packages/ncm/downloader.py", line 66, in download_song_by_song
    resize_img(os.path.join(song_download_folder, cover_file_name))
  File "/usr/lib/python3.7/site-packages/ncm/file_util.py", line 19, in resize_img
    img.save(file_path, quality=quality)
  File "/usr/lib/python3.7/site-packages/PIL/Image.py", line 2088, in save
    save_handler(self, fp, filename)
  File "/usr/lib/python3.7/site-packages/PIL/JpegImagePlugin.py", line 630, in _save
    raise IOError("cannot write mode %s as JPEG" % im.mode)
OSError: cannot write mode P as JPEG

样例: 蝉证序

处理方法: 先将img转为rgb模式,不再判断是否为png 原函数:

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)
        if img.format == 'PNG':
            img = img.convert('RGB')
        img.save(file_path, quality=quality)

修改:

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

    img=img.convert('RGB')

    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)
codezjx commented 4 years ago

已修复,非常感谢~