2014-03-12 94 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