使用Pillow(PIL)在Python中生成图像 [英] Generating image in Python using Pillow (PIL)

查看:349
本文介绍了使用Pillow(PIL)在Python中生成图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python(v2.7.2)和Pillow(v2.4.0)生成100x100的全黑图像,但结果却很奇怪.

I'm trying to generate a 100x100 all-black image with Python (v2.7.2) and Pillow (v2.4.0) and I get a very weird result.

这是我的代码

from PIL import Image
im = Image.frombytes('L', (100, 100), bytes([0] * 100 * 100))
im.show()

这是我的结果(放大后请忽略灰色边框-它来自OS X预览版).图像应为黑色,但不是.

This is my result (zoomed-in and please ignore the grey border - it comes from OS X Preview). The image should be black, but it is not.

我在做什么错了?

推荐答案

bytes([0] * 10)的结果是字符串"[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]".因此,像素的颜色是'[''0'','' '']'符号的ASCII码.

The result of bytes([0] * 10) is the string "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]". So, the colors of your pixels are the ASCII codes of '[', '0', ',', ' ', and ']' symbols.

要获取零字节的字节字符串,请使用bytes("\x00" * 100 * 100). \x00是具有十六进制值00的字节.

To get the byte string of zero bytes use bytes("\x00" * 100 * 100) instead. Here \x00 is the byte with hexadecimal value 00.

实际上,您甚至不需要bytes(...)通话. bytes是仅在Python 3.x中的类型.在Python 2.7.x中,bytes只是str的别名.

Actually you don't even need bytes(...) call. bytes is the type only in Python 3.x. In Python 2.7.x bytes is just an alias for str.

因此,最终代码应为:

from PIL import Image
im = Image.frombytes('L', (100, 100), "\x00" * 100 * 100)
im.show()

这篇关于使用Pillow(PIL)在Python中生成图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆