将图像转换为字节数组的 Python 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22351254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:46:39  来源:igfitidea点击:

Python Script to convert Image into Byte array

python

提问by Akash Bhardwaj

I am writing a Python script where I want to do bulk photo upload. I want to read an Image and convert it into a byte array. Any suggestions would be greatly appreciated.

我正在编写一个 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', 'Cs$corp@123')

回答by cptPH

i don't know about converting into a byte array, but it's easy to convert it into a string:

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

import base64

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

Source

来源

回答by Thomas Baruchel

Use bytearray:

使用bytearray

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

You can also have a look at structwhich can do many conversions of that kind.

您还可以查看struct,它可以进行许多此类转换。

回答by perillaseed

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

I just use this for add a image to clipboard in windows.

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

回答by Rami Alloush

This works for me

这对我有用

# 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