用于将Image转换为Byte数组的Python脚本

Aka*_*waj 31 python

我正在编写一个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')
Run Code Online (Sandbox Code Playgroud)

Tho*_*hel 45

用途bytearray:

with open("img.png", "rb") as image:
  f = image.read()
  b = bytearray(f)
  print b[0]
Run Code Online (Sandbox Code Playgroud)

您还可以查看一下可以执行此类转换的struct.

  • 如何执行此转换的相反操作,即将字节数组转换为图像? (2认同)

cpt*_*tPH 10

我不知道转换成字节数组,但很容易将其转换为字符串:

import base64

with open("t.png", "rb") as imageFile:
    str = base64.b64encode(imageFile.read())
    print str
Run Code Online (Sandbox Code Playgroud)

资源


per*_*eed 6

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

我只是用它为Windows中的剪贴板添加图像。


Ram*_*ush 5

这对我有用

# 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
Run Code Online (Sandbox Code Playgroud)