使用Python open函数读取PNG图片时遇UnicodeDecodeError错误求助
Hey there! That error pops up because you're trying to read a PNG file as if it were plain text—and PNGs are binary files, not text files. Let me break this down and show you how to fix it.
The Root Problem
When you use open('here.png') without specifying a mode, Python defaults to text mode ('r'). In text mode, it tries to decode the file's bytes into a string using your system's default character codec. But PNG files have binary data that doesn't map to valid text characters, so you get that UnicodeDecodeError.
The Quick Fix
You need to open the file in binary read mode instead. Just add 'rb' as the second argument to open():
img = open('here.png', 'rb').read()
This tells Python to read the raw bytes of the file without trying to decode them into text—perfect for images, videos, zip files, and other non-text formats.
Bonus: Working with the Image Directly
If you're planning to manipulate the image (crop, resize, edit pixels, etc.), using the open() function to read bytes is a bit low-level. The Pillow library (a popular image processing tool for Python) makes this way easier:
from PIL import Image # Open the image directly for editing img = Image.open('here.png') # Example: Show the image img.show()
Just make sure you install Pillow first with pip install pillow if you haven't already.
内容的提问来源于stack exchange,提问作者WhatAMesh

