简体   繁体   中英

Encoding issues when converting Pyhon 2 to Python 3 (using lmdb)

I'm trying to convert some code in Python 2 to Python 3. I'm not too familiar with the changes in how encoding works between the two versions of Python, so was not exactly sure how to word the question.

Basically in Python 2 the code looks like this:

image_key = "image_3"
env = lmdb.open(some arguments here)

with env.begin(write=False) as txn:
    img_tmp = txn.get(image_key)
    img = Image.open(StringIO(img_tmp))

In Python 2, "img_tmp" would be a string object with unreadable characters (printing it gives me a mess: PNGIHDR A gAMA ? acHRMz& u0 `...). And the next line would open the image as a pillow image.

In Python 3, the line txn.get() would give me an error "TypeError: Won't implicitly convert Unicode to bytes; use .encode()" so II followed the suggestion and converted the line to:

img_tmp = txn.get(img_key.encode())

However, img_tmp is now a bytes object that reads something like this: "b'\\x89PNG\\r\\n\\x1a\\n\\x00\\ ..."

And the next line would no longer open the image. Any suggestions on how to change the code to get it to work?

您就BytesIO :只需使用BytesIO而不是StringIO ,因为您的二进制数据是bytes而不是str

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM