Skip to main content

Converts pictures into ASCII art

Project description

ASCII Magic

Python package that converts images into ASCII art for terminals and HTML. Thanks to Colorama it's compatible with the Windows terminal.

Code based on ProfOak's Ascii Py.

Changelog

v2.1

  • DALL•E support

v2.0

  • Complete rewrite, only supports OOP, no longer compatible with 1.x
  • Added support for foreground color
  • Test suite compatible with PyTest

v1.6

  • OOP functionality
  • to_file()

How to install

pip install ascii_magic

Quickstart

import ascii_magic

my_art = ascii_magic.from_image('images/moon.jpg')
my_art.to_terminal()

Result:

ASCII Magic example

Available functions

quick_test()

Loads a random Unsplash picture with the default parameters and prints it to the terminal, allowing you to verify in a single line of code that everything is running O.K.

ascii_magic.quick_test() -> None

from_image()

Creates an AsciiArt object from an image file.

from_image(path: str) -> AsciiArt

Parameters:

  • path (str): an image file compatible with Pillow, such as a jpeg or png

Example:

import ascii_magic

my_art = ascii_magic.from_image('images/lion.jpg')
my_art.to_terminal(columns=200, back=ascii_magic.Back.BLUE)

Result:

ASCII Magic TERMINAL mode example

Example:

import ascii_magic

my_art = ascii_magic.from_image('images/lion.jpg')
my_art.to_html_file('ascii_art.html', columns=200, width_ratio=2)

Result:

ASCII Magic HTML mode example

Example:

import ascii_magic

my_art = ascii_magic.from_image('images/lion.jpg')
my_art.to_terminal(columns=200, monochrome=True)

Result:

ASCII Magic ASCII mode example

from_dalle()

Creates an AsciiArt object with DALL•E, a deep learning model that can generate realistic images from a description in natural language. Requires a DALL•E API key. The API key can be configured in the module, as described in the OpenAI documentation (openai.api_key = api_key) or through this function call.

from_dalle(
    prompt: str,
    api_key: Optional[str]
) -> AsciiArt

Parameters:

  • prompt (str): a description of an image in natural language
  • api_key (str, optional): a DALL•E API key

Example:

import ascii_magic
import os

api_key = os.environ.get('MY_DALLE_API_KEY')

my_art = ascii_magic.from_dalle('A portrait of a cow with noble clothes, digital art', api_key)
my_art.to_html_file('cow.html', columns=200)

Result:

ASCII Magic DALL•E example

from_url()

Creates an AsciiArt object from an image URL. Raises an urllib.error.URLError if something goes wrong while requesting the image, but you can also catch it as an OSError if you don't want to import urllib into your project.

from_url(url: str) -> AsciiArt

Parameters:

  • url (str): an URL which will be loaded via urllib (supports redirects)

Example:

import ascii_magic

try:
    my_art = ascii_magic.from_url('https://source.unsplash.com/800x600?nature')
except OSError as e:
    print(f'Could not load the image, server said: {e.code} {e.msg}')

from_clipboard()

Creates an AsciiArt object from the contents of the clipboard. Raises a OSError if the clipboard doesn't contain an image. Requires PyGObject under Linux.

from_clipboard() -> AsciiArt

Example:

import ascii_magic

try:
    my_art = ascii_magic.from_clipboard()
except OSError:
    print('The clipboard does not contain an image')

from_pillow_image()

Creates an AsciiArt object from an image object created with Pillow. This allows you to handle the image loading yourself.

from_pillow_image(img: PIL.Image) -> AsciiArt

Parameters:

  • img (obj): an image object created with Pillow

Example:

import ascii_magic
from PIL import Image

img = Image.open('images/lion.jpg')
my_art = ascii_magic.from_pillow_image(img)

The AsciiArt object

An AsciiArt object created by the functions explained above has the following methods: to_ascii(), to_terminal(), to_file(), to_html() and to_html_file(). These methods allow you to display the ASCII art in different ways.

AsciiArt.to_ascii()

Returns a string containing the art and, by default, control characters that allows most terminals (also known as shells) to display color.

AsciiArt.to_ascii(
    columns: int = 120,
    width_ratio: float = 2.2,
    char: Optional[str] = None,
    monochrome: bool = False,
    back: Optional[Back] = None,
    front: Optional[Front] = None
) -> str

Parameters:

  • columns (int, optional): the number of characters per row, more columns = wider art
  • width_ratio (float, optional): ASCII characters are not squares, so this adjusts the width to height ratio during generation
  • char (str, optional): instead of using many different ASCII glyphs, you can use a single one, such as '#'
  • monochrome (bool, optional): if set to True, disables the usage of control characters that display color
  • back (enum, optional): sets the background color to one of:
    • ascii_magic.Back.BLACK
    • ascii_magic.Back.RED
    • ascii_magic.Back.GREEN
    • ascii_magic.Back.YELLOW
    • ascii_magic.Back.BLUE
    • ascii_magic.Back.MAGENTA
    • ascii_magic.Back.CYAN
    • ascii_magic.Back.WHITE
  • front (enum, optional): overrides the foreground color with one of:
    • ascii_magic.Front.BLACK
    • ascii_magic.Front.RED
    • ascii_magic.Front.GREEN
    • ascii_magic.Front.YELLOW
    • ascii_magic.Front.BLUE
    • ascii_magic.Front.MAGENTA
    • ascii_magic.Front.CYAN
    • ascii_magic.Front.WHITE

Example:

import ascii_magic

my_art = ascii_magic.from_image('images/lion.jpg')
my_output = my_art.to_ascii(columns=200, back=ascii_magic.Back.BLUE)
print(my_output)

Result:

ASCII Magic TERMINAL mode example

AsciiArt.to_terminal()

Identical to AsciiArt.to_ascii(), but it also does a print() of the result, saving you one line of code ;)

AsciiArt.to_file()

Identical to AsciiArt.to_ascii(), but it also saves the result to a text file.

AsciiArt.to_file(
    path: str,
    # ... same parameters as AsciiArt.to_ascii()
) -> str

Parameters:

  • path (str): the output file path

Example:

import ascii_magic

my_art = ascii_magic.from_image('images/lion.jpg')
my_art.to_file('lion.txt', monochrome=True)

AsciiArt.to_html()

Generates HTML markup of the ASCII art. Uses the same parameters as AsciiArt.to_ascii(), except back and front colors. By default the HTML ASCII art is generated with a 16-bit palette (16 million colors).

AsciiArt.to_html(
    full_color: bool = True,
    # ... same parameters as AsciiArt.to_ascii(), except back and front colors
) -> str

Parameters:

  • full_color (bool, optional): if set to False, limits color palette to 8 colors

Example:

import ascii_magic

my_art = ascii_magic.from_image('images/lion.jpg')
my_html_markup = ascii_magic.to_html(columns=200)

Result:

ASCII Magic HTML mode example

AsciiArt.to_html_file()

Identical to AsciiArt.to_html(), but it also saves the markup to a barebones HTML file inside a <pre> tag with a bunch of default CSS styles.

AsciiArt.to_html(
    path: str,
    styles: str = '...',  # See description below
    additional_styles: str = '',
    auto_open: bool = False
    # ... same parameters as AsciiArt.to_html()
) -> str

Parameters:

  • path (str): the output file path
  • styles (str): a string with a bunch of CSS styles for the <pre> element, by default:
    • display: inline-block;
    • border-width: 4px 6px;
    • border-color: black;
    • border-style: solid;
    • background-color: black;
    • font-size: 8px;
  • additional_styles (optional): use this to add your own CSS styles without removing the default ones
  • auto_open (optional): if True, webbrowser.open() will be called on the HTML file

Example:

import ascii_magic

my_art = ascii_magic.from_image('images/lion.jpg')
ascii_magic.to_html_file('lion.html', columns=200, additional_styles='background: #222;', auto_open=True)

Licence

Copyright (c) 2020 Leandro Barone.

Usage is provided under the MIT License. See LICENSE for the full details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ascii_magic-2.1.tar.gz (12.4 kB view hashes)

Uploaded Source

Built Distribution

ascii_magic-2.1-py3-none-any.whl (12.3 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page