Skip to content
Advertisement

Saving an output of a program in python as an image

I need to save an image of a chessboard, like the one created by this code:

import chess
board = chess.Board()
board

The output is the starting chessboard:

chessboard

How can I save this image and print it (for example inside a function)? Is there a unique package for these things in python? If I try to print the board (typing print (board)) I get a string that presents the chessboard, not the same photo.

Advertisement

Answer

You can use sys to write the output into an svg file and then save it. First use chess.svg to create the svg file of chess board and then assign svg in some variable and write that data in the file.

import sys
import chess.svg
import chess
board = chess.Board()
boardsvg = chess.svg.board()
outputfile = open('name.svg', "w")
outputfile.write(boardsvg)
outputfile.close()

I hope that helps!

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement