2014-03-12 29 views
13

我正在編寫一個Python腳本,用於執行批量照片上傳。 我想讀取圖像並將其轉換爲字節數組。任何建議將不勝感激。用於將圖像轉換爲字節數組的Python腳本

#!/usr/bin/python 
import xmlrpclib 
import SOAPpy, getpass, datetime 
import urllib, cStringIO 
from PIL import Image 
from urllib import urlopen 
import os 
import io 
from array import array 
""" create a proxy object with methods that can be used to invoke 
    corresponding RPC calls on the remote server """ 
soapy = SOAPpy.WSDL.Proxy('localhost:8090/rpc/soap-axis/confluenceservice-v2?wsdl') 
auth = soapy.login('admin', '[email protected]') 
+1

你爲什麼要這樣做?這將如何幫助你上傳? theres沒有足夠的數據有意義的答案 – WeaselFox

+0

@WeaselFox:我想讀取一個圖像文件並將其轉換爲Byte數組。 –

+0

#pictureData = xmlrpclib.Binary(open('C:/BulkPhotoUpload/UserPhotos/admin.png')。read())。decode('utf-8') url ='C:/ BulkPhotoUpload/UserPhotos/admin。 png' pictureData = unicode(str(open(url,「rb」))) print type(pictureData) profilePictureAdded = soapy.addProfilePicture(auth,'admin','avatar.png','image/png', pictureData) if profilePictureAdded: print「成功添加新的個人資料圖片...」 其他: 打印「無法添加新的個人資料圖片...」 –

回答

3

我不知道轉換成字節數組,但它很容易把它轉換成字符串:

import base64 

with open("t.png", "rb") as imageFile: 
    str = base64.b64encode(imageFile.read()) 
    print str 

Source

25

使用bytearray

with open("img.png", "rb") as imageFile: 
    f = imageFile.read() 
    b = bytearray(f) 

print b[0] 

你也可以看看struct,它可以做很多轉換那樣。

+0

順便說一句。使用可以直接解釋數據的圖像格式來做到這一點更有意義,例如使用PNM系列(PBM,PGM,PPM)就是如此。 –

2
with BytesIO() as output: 
    from PIL import Image 
    with Image.open(filename) as img: 
     img.convert('RGB').save(output, 'BMP')     
    data = output.getvalue()[14:] 

我只是用它來添加一個圖像剪貼板在Windows中。

+0

所以BytesIO()來自io包(io.BytesIO())。我試過這個代碼,但它給了我錯誤AttributeError:__exit__ – wordsforthewise

+0

錯誤是在Image.open()行,順便說一下 – wordsforthewise