Convert JSON to PNG in Python
Last Updated :
07 Mar, 2024
We are given JSON data and our task is to convert JSON to PNG in Python using different approaches. In this article, we will explore how to convert JSON data into PNG images using Python.
Convert JSON to PNG in Python
Below are some of the ways by which we can convert JSON to PNG in Python:
- Using pil Library
- Using Matplotlib Library
Convert JSON to PNG in Python Using PIL (Pillow) Library
The Pillow library, a fork of the original Python Imaging Library (PIL), is a powerful image-processing library in Python. To use this library for converting JSON to PNG, you can follow the code below: This example uses the Pillow library to create an image, draw the JSON text on it, and save the image as a PNG file.
Python3
from PIL import Image, ImageDraw, ImageFont
import json
def json_to_png(json_data, output_file):
json_str = json.dumps(json_data, indent = 4 )
image = Image.new( 'RGB' , ( 800 , 600 ), 'white' )
draw = ImageDraw.Draw(image)
font = ImageFont.load_default()
draw.text(( 10 , 10 ), json_str, font = font, fill = 'black' )
image.save(output_file)
sample_json = { "name" : "John Doe" , "age" : 30 , "city" : "Example City" }
json_to_png(sample_json, "example1_output.png" )
print ( 'successfully converted JSON to PNG' )
|
Output:
successfully converted JSON to PNG
Convert JSON to PNG Using Matplotlib Library
Matplotlib is a popular plotting library in Python. Though primarily designed for creating charts and graphs, it can be repurposed to visualize JSON data as an image. Here’s an example: This example utilizes Matplotlib to create a text plot, remove axis elements, and save the plot as a PNG file.
Python3
import matplotlib.pyplot as plt
import json
def json_to_png(json_data, output_file):
json_str = json.dumps(json_data, indent = 4 )
plt.text( 0.5 , 0.5 , json_str, ha = 'center' , va = 'center' , wrap = True )
plt.axis( 'off' )
plt.savefig(output_file, bbox_inches = 'tight' , pad_inches = 0 )
sample_json = { "name" : "John Doe" , "age" : 30 , "city" : "Example City" }
json_to_png(sample_json, "example2_output.png" )
print ( "successfully converted JSON to PNG" )
|
Output:
successfully converted JSON to PNG
Conclusion
In this article, we explored some different approaches to convert JSON data to PNG images using Python. Whether using image manipulation libraries like Pillow, repurposing plotting libraries like Matplotlib, these examples provide flexibility for various use cases. Depending on your specific requirements and preferences, you can choose the approach that best fits your needs when working with JSON data visualization in Python.
Share your thoughts in the comments
Please Login to comment...