You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python open函数读取PNG图片时遇UnicodeDecodeError错误求助

Fixing UnicodeDecodeError When Reading PNG Files in Python

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:44:21