Search code examples
pythonpython-3.xmatplotlibpng

How to Save Figure as PNG Byte Array With Decimal Formatting


I have some data I'm visualizing with a MatPlotLib figure. I want to be able to convert the figure into a byte array that is formatted with PNG decimal values. https://www.w3.org/TR/PNG-Structure.html

fig = plt.figure(figsize=(16,16))
ax = fig.add_subplot(projection='3d')
ax.voxels(space, facecolors = rgb_input)
plt.axis('off')
fig.patch.set_alpha(0.25)
ax.patch.set_alpha(0.25)

I know how to save it as a PNG and convert that into a byte array, but I want to be able to make the byte array directly.

I've tried using this to get the byte array directly, but it doesn't return PNG decimal values:

buf = io.BytesIO()
plt.savefig(buf, format = 'png')
buf.seek(0)
data = buf.read()

EDIT: Upon further research, I've found that the data value is formatted as an ASCII byte array. Is there a way to convert it into a decimal byte array?


Solution

  • PNG images are binary files usually represented in ASCII or hexadecimal, to convert the byte array into a decimal representation, you can simply do that with Python's built-in functions.

    import io
    import matplotlib.pyplot as plt
    import numpy as np
    
    space = np.random.rand(5,5,5) > 0.5
    rgb_input = np.random.rand(5,5,5,3)
    
    fig = plt.figure(figsize=(16,16))
    ax = fig.add_subplot(projection='3d')
    ax.voxels(space, facecolors = rgb_input)
    plt.axis('off')
    fig.patch.set_alpha(0.25)
    ax.patch.set_alpha(0.25)
    
    buf = io.BytesIO()
    plt.savefig(buf, format = 'png')
    buf.seek(0)
    data = buf.read()
    
    decimal_values = [byte for byte in data]
    print(decimal_values)