我正在尝试将图像从 gif 格式转换为 png 格式。我是这样做的
def _gif_to_png(gif_dir, png_dir):
img_names = tf.gfile.ListDirectory(gif_dir)
for f in img_names:
# get the filename without the extension
basename = os.path.basename(f).split(".")[0]
im = Image.open(os.path.join(gif_dir,f))
transparency = im.info['transparency']
png_file_name = os.path.join(png_dir, basename+'.png')
im.save(png_file_name, transparency=transparency)
png_names = tf.gfile.ListDirectory(png_dir)
但是,我收到以下错误信息
transparency = im.info['transparency']
KeyError: 'transparency'
可能是什么问题以及如何解决?
请您参考如下方法:
当您的 GIF 不包含透明度时会发生这种情况。
transparency
Transparency color index. This key is omitted if the image is not transparent.
(http://pillow.readthedocs.io/en/5.1.x/handbook/image-file-formats.html#gif)
您如何知道 GIF 是否包含透明像素?显然,您的做法是——通过测试该 key 是否存在。你可以直接测试它,用 try..except 包围,或者用
if 'transparency' in im.info.dict():
.. do stuff ..
