注意:轉化成txt後,txt的字體使用「宋體」,不能使用「微軟雅黑」,不然圖像會變形字體
import numpy as npfrom PIL import Imageif __name__ == '__main__': image_file = 'huarun3.png' height = 100 img = Image.open(image_file) img_width, image_height = img.size print('img_width:', img_width) print('image_height:', image_height) width = int(height / image_height * img_width * 2) img = img.resize((width, height), Image.ANTIALIAS) print(img) img_l = img.convert('L') pixels = np.array(img_l) print(img_l) chars = 'MNHQ$OC?7>!:-;. ' step = 256 // len(chars) result = '' for i in range(height): for j in range(width): result += chars[pixels[i][j] // step] result += '\n' with open(image_file + '.txt', mode='w') as f: f.write(result)