使用Stepic实现图片编解码时遇AttributeError错误求助
解决Stepic图片编码时的AttributeError问题
错误原因
你的代码存在三个核心问题:
img = Image.open未调用函数,仅将Image.open函数本身赋值给img变量,传给stepic.encode的是函数对象而非PIL的Image实例,因此触发'function' object has no attribute 'copy'错误。- 保存编码后图片的逻辑完全错误:将用户输入的新文件名直接赋值给
encoded_image,覆盖了之前编码得到的图片对象,且未正确调用save()方法。 - JPG是有损压缩格式,会破坏隐写的信息,确实不适合做图片隐写,建议使用PNG、BMP这类无损格式。
修正后的代码
from PIL import Image import stepic # 获取图片路径并打开图片 img_path = input("enter name and extension of image you want to encode: ").strip() img = Image.open(img_path) # 获取待隐藏消息并转为字节流 secret_msg = input("Please enter the message you want to encode an image with: ").encode() # 执行图片隐写编码 encoded_img = stepic.encode(img, secret_msg) # 获取保存路径并保存编码后的图片 save_path = input("enter new image name with extension: ").strip() encoded_img.save(save_path) print("Encryption completed ")
关键修改点
- 调用
Image.open(img_path)打开指定图片,生成有效的Image实例 - 分离文件名变量与图片对象变量,避免覆盖编码后的图片对象
- 正确调用
encoded_img.save(save_path)完成图片保存 - 优化变量命名,提升代码可读性
内容的提问来源于stack exchange,提问作者Liam Johns
相关产品推荐
相关产品推荐

