大家幫我看看這個程式該怎么除錯啊。
一直報錯。

源代碼:
from PIL import Image
# 待隱寫圖片初始化
def makeImageEven(image):
# 得到類表[(r,g,b,t),(r,g,b,t)...]
pixels = list(image.getdata())
# 將每個像素的最低有效位初始化為0
evenPixels = [(r >> 1 << 1, g >> 1 << 1, b >> 1 << 1,t >> 1 << 1)
for [r, g, b,t] in pixels]
# 創建原圖副本
evenImage = Image.new(image.mode, image.size)
# 把擦除的像素放入副本
evenImage.putdata(evenPixels)
# 回傳初始化的隱寫圖片
return evenImage
def constLenBin(int):
# 去掉bin()回傳的二進制字串的'0b'
# 在左邊補足'0'直到字串長度為8
binary = "0"*(8-(len(bin(int))-2))+bin(int).replace('0b', '')
return binary
# 隱寫資料
def encodeDataInImage(image, data):
# 獲得最低有效位為0的圖片副本
evenImage = makeImageEven(image)
# 將被隱藏的字串轉換成二進制字串
binary = ''.join(map(constLenBin, bytearray(data, 'utf-8')))
# 資料資訊溢位圖片空間,則拋例外
# 每個像素rgba有四個分量,即四個最低有效位
if len(binary) > len(image.getdata()) * 4:
raise Exception("Error: Can't encode more than " +
len(evenImage.getdata())*4+" bits in this image. ")
# 將字符二進制位數寫入遍歷像素的最低有效位
encodedPixels = [(r+int(binary[index*4+0]), g+int(binary[index*4+1]), b+int(binary[index*4+2]), t+int(binary[index*4+3]))
if index*4 < len(binary) else (r, g, b,t) for index, (r, g, b,t) in enumerate(list(evenImage.getdata()))]
# 創建新圖存放編碼后的像素
encodedImage = Image.new(evenImage.mode, evenImage.size)
# 添加資料
encodedImage.putdata(encodedPixels)
return encodedImage
# 解碼接受圖片物件引數
def decodeImage(image):
# 獲取像素串列
pixels = list(image.getdata())
# 提取圖片中所有最低有效位中的資料
binary = ''.join([str(int(r >> 1 << 1 != r))+str(int(g >> 1 << 1 != g))+str(
int(b >> 1 << 1 != b))+str(int(t >> 1 << 1 != t)) for (r, g, b, t) in pixels])
# 找到資料截止處的索引
# 中文字符utf-8兩個位元組,16個二進制位
locationDoubleNull = binary.find('0000000000000000')
# 不足位補零
endIndex = locationDoubleNull + \
(8-(locationDoubleNull % 8)
) if locationDoubleNull % 8 != 0 else locationDoubleNull
data = binaryToString(binary[0:endIndex])
return data
# 位位元組->字符
# 將提取出來的二進制字符轉換為隱藏的文本
def binaryToString(binary):
index = 0
string = []
# 提取碼點真正的字符資料
# 區分位元組標志與字符資料
def rec(x, i): return x[2:8] + \
(rec(x[8:], i-1) if i > 1 else '') if x else ''
# 獲取字符資料
def fun(x, i): return x[i+1:8] + rec(x[8:], i-1)
while index + 1 < len(binary):
# 分析位元組序列
# 字符的位元組資料中,第一個位元組開頭 1 的數目便是字符所占的位元組數
chartype = binary[index:].index('0')
length = chartype*8 if chartype else 8
# chr()將unicode碼點轉為對應字符
string.append(chr(int(fun(binary[index:index+length], chartype), 2)))
index += length
return ''.join(string)
if __name__ == '__main__':
encodeDataInImage(Image.open('coffee.png'),'你好世界, hello World!').save('encodeImage.png')
print(decodeImage(Image.open("encodeImage.png")))
uj5u.com熱心網友回復:
函式傳入的list處理4個元素,你穿的只有三個,print一下pixels看一下uj5u.com熱心網友回復:
這個代碼只支持png格式圖片轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/89404.html
上一篇:Mac系統下用pyinstaller打包運行結果不正確
下一篇:爬蟲
