Ofir
Ofir

Reputation: 771

Saving 2d-list as an image

I have 2d-list that each element is an Integer number, and I want to save its data as an image. Please notice that I don't want to save it as pixels, but just as numbers.

For example:

L =  1 2 3
     4 5 6
     7 8 9

Then, I want to save it as a picture that contains these numbers (not as colors, etc..). How can I achieve this?
Thanks in advance!

Upvotes: 0

Views: 369

Answers (1)

Vasilis G.
Vasilis G.

Reputation: 7844

I am not quite sure whether this is what you're asking, but one way to achieve it by using Pillow, a Python Image Library that provides you with functionality to write text to an image. So, in order to store your list of number on an image, you can use the following code, provided that you have Pillow installed:

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw 

L =  [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

size = 300
img = Image.new("RGB", (size,size), 'white')
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("arial.ttf", 48)
for i in range(0,size,size//3):
    for j in range(0,size,size//3):
        print(i//100,j//100)
        draw.text((i+size//9, j+size//9), str(L[i//100][j//100]), (0,0,0), font=font)
img.save('numbers.jpg')

The result image will be:

enter image description here

Upvotes: 1

Related Questions