DEV Community

Cover image for Turn photos into pixel art with Python
natamacm
natamacm

Posted on

Image to Pixel Art Turn photos into pixel art with Python

Make your photos looks like pixel art using Python. This works with Python >= 2.6, Python >= 3.2.

You can use the module pixelate to do that.

Installation can be done with pip:

pip install pixelate
Enter fullscreen mode Exit fullscreen mode

Example with command line

pixelate --input=img/bps.jpg --output=img/bps.png --pixel-size=10
Enter fullscreen mode Exit fullscreen mode

The module has one method pixelate, so if you import it you can call the method pixelate(input_file_path, output_file_path, pixel_size).

The code of this method is:

from PIL import Image

def pixelate(input_file_path, output_file_path, pixel_size):
    image = Image.open(input_file_path)
    image = image.resize(
        (image.size[0] // pixel_size, image.size[1] // pixel_size),
        Image.NEAREST
    )
    image = image.resize(
        (image.size[0] * pixel_size, image.size[1] * pixel_size),
        Image.NEAREST
    )

    image.save(output_file_path)
Enter fullscreen mode Exit fullscreen mode

Now it wouldn't let me call the method from the module, so instead I copied the function and changed it a bit:

from PIL import Image

def pixelate(input_file_path, pixel_size):
    image = Image.open(input_file_path)
    image = image.resize(
        (image.size[0] // pixel_size, image.size[1] // pixel_size),
        Image.NEAREST
    )
    image = image.resize(
        (image.size[0] * pixel_size, image.size[1] * pixel_size),
        Image.NEAREST
    )

    image.show()

pixelate("fedora.jpg",16)
Enter fullscreen mode Exit fullscreen mode

pixel art

Latest comments (0)