2016-07-01 124 views
0

我想讀取每個字節的圖像字節並獲取每個字節的(0-255)值。我試圖用此代碼打印:如何讀取一個字節並轉換爲int(0-255)

f = open("my_directory_with_image.png", "rb") 
try: 
    byte = f.read(1) 
    while byte != "": 
     # Do stuff with byte. 
     byte = f.read(1) 
     print int(byte) 
finally: 
    f.close() 

,但我得到這個錯誤:

invalid literal for int() with base 10:

任何想法?謝謝!

回答

0

使用struct模塊。

import struct 
value = struct.unpack('B', byte[0])[0] 

解包將始終返回一個元組,即使您只是解包一個項目。

此外,這似乎是重複的This SO question