我正在编写一个Python脚本,我想要批量上传照片。 我想读取一个Image并将其转换为字节数组。任何建议都将不胜感激。
#!/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', 'Cs$corp@123')
答案 0 :(得分:40)
使用bytearray
:
with open("img.png", "rb") as image:
f = image.read()
b = bytearray(f)
print b[0]
您还可以查看struct,可以进行多次转换。
答案 1 :(得分:7)
我不知道转换为字节数组,但很容易将其转换为字符串:
import base64
with open("t.png", "rb") as imageFile:
str = base64.b64encode(imageFile.read())
print str
答案 2 :(得分:3)
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中的剪贴板。
答案 3 :(得分:2)
这对我有用
# Convert image to bytes
import PIL.Image as Image
pil_im = Image.fromarray(image)
b = io.BytesIO()
pil_im.save(b, 'jpeg')
im_bytes = b.getvalue()
return im_bytes