Writing a dict into a png file
Question: I'm a beginner on python and only have rudiments of this language, the
question might not be a hard one but it's bogging me down.

Now I have a 'dict' data structure, let's assume it being {(0,0): 'red'}, just
one element.

I want to draw a unit square of red color centered at point (0,0) on the 2D
plane, and output the result as a .png file. Once this is down, one can easily
do the case of many many more points in the dict.

I think the code should be very simple( it's best not to use libs, for example
matplotlib cairo .. etc), but I do not know how to interact with graphics, can
anyone give me a hint?

I googled but the results mostly are matplotlib, pyplot... that use lib files,
I think there must be a simple solution with only plain python code, so I post
here for help.


Answer: Personally I find cairo the easiest one. All you need is to set up canvas and
fill it with shapes. For a rectangular you will need its X, Y position as
starting points and width and height to complete drawing. Colors are used in
rgb float. You will have to convert named colors to rgb if you want to use
them.

I made an example for you:

    
    
    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    import cairo
    
    # You need colors in rgb floats
    
    Dict= {(70,60): (1,1,0), (100,90): (0,1,0), (130,120): (0,0,1)}
    your_dict={(0,0): (1,0,0)}
    
    radius=10 # The radius of the dot
    
    w=100 # width of the square
    h=100 # height of the square
    
    WIDTH, HEIGHT = 200, 200 # Canvas size
    
    surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
    context = cairo.Context (surface)
    
    # Background Neutral Gray ----------
    context.set_source_rgb(0.25, 0.25, 0.25)
    context.rectangle(0, 0, WIDTH, HEIGHT)
    context.fill()
    
    
    # Your Square -----------------------
    
    for e in your_dict:
        posX = e[0]
        posY = e[1]
    
        r = your_dict[e][0]
        g = your_dict[e][1]
        b = your_dict[e][2]
    
        context.set_source_rgb(r, g, b) # rgb color
        context.rectangle(posX, posY, w, h)
        context.fill()
    
    
    # White Example Circle -------------------
    context.set_source_rgb(1, 1, 1) # rgb color
    context.arc(20, 20, 10.0, 0, 360)
    context.fill()
    
    
    # Dots from Dict -------------------
    
    for e in Dict:
    
        posX = e[0]
        posY = e[1]
    
        r = Dict[e][0]
        g = Dict[e][1]
        b = Dict[e][2]
    
        context.set_source_rgb(r, g, b) # rgb color
        context.arc(posX, posY, radius, 0, 360)
        context.fill()
    
    surface.write_to_png ("img.png") # Output to PNG
    

You will get an image: <http://oi59.tinypic.com/2yy2iv7.jpg>

