英文:
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?
英文:
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?
答案1
得分: 2
PNG 图像通常以 ASCII 或十六进制表示的二进制文件,要将字节数组转换为十进制表示,您可以使用 Python 的内置函数来完成。
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)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论