我正在试验PIL,具体地说,是从字符串生成图像
我有以下代码:
from __future__ import unicode_literals
import array
from PIL import Image
photo_data = "35c1f6ebc3ef2d424ced351b65be8c396f8396d69411d7e7185f2a5e9eaab7da"
scale = 16 ## equals to hexadecimal
num_of_bits = 8
allbits = []
for i in range(len(photo_data)):
photobits = bin(int(photo_data[i], scale))[2:].zfill(num_of_bits)
allbits.append(photobits)
photo_image = Image.frombytes("1", (8, 64), "".join(allbits).replace("1","F"), "raw")
photo_image.show()
这段代码中没有错误,但我看到的图像对我来说并不正确
我希望顶行是“00000011”,但它是“11001111”
它可能与frombytes函数的参数有关。但是什么D
实际上,我要做的是将photo_data
字符串中的每个字符表示为图像中的一行,每个启用的位都是黑色的
也许我走错了方向,有更简单的方法吗
您现在拥有的是一系列行,它们表示ASCII字符“0”和“F”的二进制可视化,因为这就是您的列表所包含的内容。”0”表示00110000,“F”表示01000110。这些与您的行匹配,白色为1位,黑色为0位
现在,您正试图用一个字节大小的字符来表示每个像素。但是
frombytes
实际上期望每比特一个像素,这意味着一个字符代表八个像素。因此,您应该使用序号值等于照片数据字符串值的字符填充数组。因此,例如“d”不应翻译为“13”或“00001101”,而应翻译为第十三个ASCII字符“\r”。通过将转换为int,然后使用chr
将其转换回string,可以相当轻松地执行此转换结果:
如果您希望白色和黑色对应于1和0,而不是相反,则可以通过将整数值与b11111111进行异或来反转整数值
结果:
相关问题 更多 >
编程相关推荐