Fundamentals 4 min read

Convert PNG Images to ASCII Art Using Python and Pillow

This tutorial demonstrates how to convert a PNG image into ASCII art by mapping pixel colors to characters, installing the Pillow library, and running a Python script that processes the image and outputs the result either to the console or a file.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Convert PNG Images to ASCII Art Using Python and Pillow

This article explains how to transform a PNG image into an ASCII art representation using Python's Pillow library.

It first describes the concept that each pixel's color can be mapped to a character, then lists the required preparation, namely installing Pillow via pip install pillow .

The core implementation is provided as a Python script that parses command‑line arguments, defines a class to map RGB values to characters, resizes the image, builds the ASCII string, and optionally writes the result to a file. The complete code is:

#! /usr/bin/python
#coding:utf8

import argparse
from PIL import Image

def handle_command():
    '命令行参数处理'
    parser = argparse.ArgumentParser()
    parser.add_argument('filename',help = '图片的路径')
    parser.add_argument('-o','--output',help = '是否输出文件')
    parser.add_argument('--width',type = int,default = 80)
    parser.add_argument('--heigth',type = int,default = 80)
    return parser.parse_args()

args = handle_command()

class Ptrancefrom(object):
    '实现将图片转化为字符'
    def __init__(self,img,width,heigth):
        self.img = img
        self.width = width
        self.heigth = heigth
        self.ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
    def get_char(self,r,b,g,alpha = 256):
        '将256范围的灰度值映射到70个字符上'
        if alpha == 0:
            return ' '
        length = len(self.ascii_char)
        gray = int(0.2126 *r + 0.7152*g + 0.0722*b)
        unit = (256.0 + 1)/length
        return self.ascii_char[int(gray/unit)]
    def print_picture(self):
        '打印图形'
        im = Image.open(self.img)
        im = im.resize((self.width,self.heigth),Image.NEAREST)
        txt = ""
        for i in range(self.heigth):
            for j in range(self.width):
                txt += self.get_char(*im.getpixel((j,i)))
            txt += '\n'
        print txt
    def write_to_file(self):
        '将生成的字符图片写入到文件'
        if args.output:
            with open(args.output,'w') as f:
                f.write(txt)
        else:
            with open('output.txt','w') as f:
                f.write(txt)

pic = Ptrancefrom(args.filename,args.width,args.heigth)
pic.print_picture()

Run the script with desired dimensions, for example:

python prog3.py --width 45 --heigth 45 ascii_dora.png

The article also shows the original image and the resulting ASCII art output.

pythonCommand-linepillowascii art
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.