2017-03-10 92 views
0

我試圖將圖像發送到打印機以使用Python腳本進行打印。我在語言方面沒有太多的經驗,並從其他一些人那裏獲得了一些技巧,而且我目前遇到了一個問題,那就是我一直收到一個錯誤,說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照片以不同的方式?謝謝。

回答

3

我認爲這個問題是,你與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')

+0

正好。 ''不是有效的文件名。 – Aaron

+0

當然啊......非常感謝 – Yellowman94

1

如果您想讀取文件的內容,那麼您只需傳遞文件名即可。相反,您將其加載到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)