Welcome, guest | Sign In | My Account | Store | Cart

This recipe shows a simple example of how to use pngcanvas, a pure Python library for PNG image creation.

Python, 31 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/env python

from __future__ import (
    absolute_import, division, print_function, unicode_literals
)

import io
import logging

from pngcanvas import *

BUFSIZE = 8*1024  # Taken from filecmp module
HEIGHT = WIDTH = 512

logging.debug("Creating canvas: %d, %d", WIDTH, HEIGHT)
c = PNGCanvas(WIDTH, HEIGHT, color=(0xff, 0, 0, 0xff))
c.rectangle(0, 0, WIDTH - 1, HEIGHT - 1)

logging.debug("Generating gradient...")
c.vertical_gradient(1, 1, WIDTH - 2, HEIGHT - 2,
    (0xff, 0, 0, 0xff), (0x20, 0, 0xff, 0x80))

logging.debug("Drawing some lines...")
c.color = bytearray((0, 0, 0, 0xff))
c.line(0, 0, WIDTH - 1, HEIGHT - 1)
c.line(0, 0, WIDTH / 2, HEIGHT - 1)
c.line(0, 0, WIDTH - 1, HEIGHT / 2)

with open("try_pngcanvas.png", "wb") as png_fil:
    logging.debug("Writing to file...")
    png_fil.write(c.dump())

pngcanvas seems like a good library for creating PNG images via Python, but at the time I created the recipe, it did not seem to have a simple example that showed how to use it. So I modified the program test_pngcanvas.py from the pngcanvas package, which is used as test of the package, to make a basic example of how to use pngcanvas.

1 comment

Vasudev Ram (author) 10 years, 2 months ago  # | flag