from PIL import Image def decode(image): #得到图片的大小 width, height = image.size ls = [] for i in range(height): for j in range(width): #获得每个位置上的rgb值 r, g, b = image.getpixel((j, i)) #获得每个像素对应的汉字字符 word_number = (r << 16) + (g << 8) + b word_string = chr(word_number) ls.append(word_string) #将列表合成为字符创 text_result = "".join(ls) return text_result def main(): #打开图片 image = Image.open("C:/users/mike1/desktop/PictureForText.png", "r") text = decode(image) with open("C:/users/mike1/desktop/PictureToText.txt", "w", encoding = "utf-8") as f: f.write(text) if __name__ == "__main__": main()
与原文本一模一样,文件大小为1.74M,比原图片大。