代码
from PIL import Image
ASCII_CHARS = "@%#*+=-:. " def resize_image ( image, new_width= 100 ) : width, height = image. sizeratio = height / widthnew_height = int ( new_width * ratio) resized_image = image. resize( ( new_width, new_height) ) return resized_imagedef grayify ( image) : grayscale_image = image. convert( "L" ) return grayscale_imagedef pixels_to_ascii ( image) : pixels = image. getdata( ) characters = "" . join( [ ASCII_CHARS[ pixel // 25 ] for pixel in pixels] ) return charactersdef main ( new_width= 100 ) : image_path = input ( "请输入图片的路径: " ) try : image = Image. open ( image_path) except Exception as e: print ( f"无法打开图片: { e} " ) return new_image_data = pixels_to_ascii( grayify( resize_image( image, new_width) ) ) pixel_count = len ( new_image_data) ascii_image = "\n" . join( [ new_image_data[ index: ( index + new_width) ] for index in range ( 0 , pixel_count, new_width) ] ) print ( ascii_image) with open ( "ascii_image.txt" , "w" ) as f: f. write( ascii_image) if __name__ == "__main__" : main( )
效果
原图
效果图