使用Tkinter打开JPG并通过Pillow加水印时遭遇UnicodeDecodeError
解决UnicodeDecodeError:charmap无法解码字节的问题
问题描述
运行图片加水印代码时触发编码错误:
line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 644: character maps to <undefined>
直接传入图片路径时功能正常,但通过文件选择对话框选文件时出错,问题集中在以下代码段:
filename = filedialog.askopenfile(filetypes=[('JPG Files', '*.jpg')]) if filename: img = Image.open(filename)
问题原因
askopenfile()默认以文本模式打开文件,而图片属于二进制文件,文本模式读取会破坏文件结构并触发编码解析错误。
修复方案
有两种可行的修改方式:
方式1:获取文件路径字符串(推荐)
用askopenfilename()替代askopenfile(),直接拿到文件路径后再打开图片,和你直接传入路径的逻辑一致:
filename = filedialog.askopenfilename(filetypes=[('JPG Files', '*.jpg')]) if filename: img = Image.open(filename)
方式2:指定二进制模式打开文件
如果需要保留文件对象的使用方式,打开时指定mode='rb'(只读二进制模式):
filename = filedialog.askopenfile(filetypes=[('JPG Files', '*.jpg')], mode='rb') if filename: img = Image.open(filename)
修改后重新运行代码,即可正常通过对话框选择图片并添加水印。
内容的提问来源于stack exchange,提问作者Alexis P
相关产品推荐
相关产品推荐

