尝试使用 Python(和 PIL)打印

Trying to Print With Python (and PIL)

我正在尝试使用 Python 脚本将图像发送到打印机进行打印。我对这门语言并没有太多的经验,也从其他一些人那里得到了一些提示,但我目前遇到的问题是我不断收到错误消息,说 PIL 中的文件丢失了。这是我的代码:

from PIL import Image
from PIL.ExifTags import TAGS
import socket
import sys
from threading import Thread

def print_bcard(HOST):
    print 'Printing business card'
    card_pic = Image.open("/home/nao/recordings/cameras/bcard.jpg")
    HOST = '192.168.0.38'
    PORT = 9100  
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    f = open(str(card_pic), 'rb')  #open in binary
    l = f.read(1024)
    while (l):
        s.send(l)
        l = f.read(1024)
    f.close()

    s.close()

print_bcard('192.168.0.38')

我不断收到的错误是:

IOError: [Errno 22] invalid mode ('rb') or filename:'<PIL.JpegImagePlugin.JpegImageFile 
image mode=RGB size=4032x2268 at 0x30C8D50>'

有谁知道发生了什么事,如果不知道的话,还有一种不使用 PIL 访问照片的不同方式吗?谢谢

如果你想读取文件的内容,那么你只需传递文件名。相反,您将它加载到 PIL Image 中,然后将图像传递给文件 open() 函数,这没有任何意义。

尝试:

with open("/home/nao/recordings/cameras/bcard.jpg", 'rb') as f:
    l = f.read(1024)
    while (l):
        s.send(l)
        l = f.read(1024)

我认为问题在于您在此处使用 PIL 打开图像:
card_pic = Image.open("/home/nao/recordings/cameras/bcard.jpg")
而不是尝试在此处打开文件:
f = open(str(card_pic), 'rb') #open in binary
但是 str(card_pic) 试图将 PIL 图像对象转换为字符串,它不会返回文件名。 试试这一行:
f = open("/home/nao/recordings/cameras/bcard.jpg", 'rb')