擅长:python、mysql、java
<p>下面是一个使用<code>frombytes</code>的示例。这只是使用纯Python,而不是Numpy。如果使用Numpy创建RGB值,那么可以使用<code>Image.fromarray</code>方法将Numpy数据转换为PIL图像。在</p>
<p>这里的重要步骤是将RGB值列表转换为<code>bytes</code>对象,这很容易通过将其传递给<code>bytes</code>构造函数来完成。在</p>
<pre><code>from colorsys import hsv_to_rgb
from PIL import Image
# Make some RGB values.
# Cycle through hue vertically & saturation horizontally
colors = []
for hue in range(360):
for sat in range(100):
# Convert color from HSV to RGB
rgb = hsv_to_rgb(hue/360, sat/100, 1)
rgb = [int(0.5 + 255*u) for u in rgb]
colors.extend(rgb)
# Convert list to bytes
colors = bytes(colors)
img = Image.frombytes('RGB', (100, 360), colors)
img.show()
img.save('hues.png')
</code></pre>
<p><strong>输出</strong></p>
<p><a href="https://i.stack.imgur.com/l6hbN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/l6hbN.png" alt="hue & saturation demo image"/></a></p>