'utf-8' codec can't decode byte 0xff in position 0

时间:2022-07-23
本文章向大家介绍'utf-8' codec can't decode byte 0xff in position 0,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

今天使用语句

image_raw_data_jpg = tf.gfile.FastGFile('../test_images/test_1.jpg', 'r').read()

读取图片文件的时候遇到了以下问题:

'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

原因:

0x92 即 10010010,UTF8 中编码一个字符的第一个字节(start byte)只可能是 0xxxxxxx、110xxxxx、1110xxx、11110xxx……而后面的字节只可能是 10xxxxxx。也就是说 0x92 只能作为后面的字节,却出现在了第一个字节的位置。

出现这种问题绝大部分情况是因为文件不是 UTF8 编码的(例如,可能是 GBK 编码的),而系统默认采用 UTF8 解码。解决方法是改为对应的解码方式。

极少数情况是因为文件损坏了或者和一部分非 UTF8 编码混在一起,可以修复文件或采用 replace 等方式解码。

解决方案

将'r'改为'rb'的形式,即:

image_raw_data_jpg = tf.gfile.FastGFile('../test_images/test_1.jpg', 'rb').read()

参考文献:

https://segmentfault.com/q/1010000004268196