【问题标题】:Python Script to convert Image into Byte array将图像转换为字节数组的 Python 脚本
【发布时间】:2014-03-12 12:16:05
【问题描述】:

我正在编写一个 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')

【问题讨论】:

  • 你为什么想要那个?这将如何帮助您上传?没有足够的数据得出有意义的答案
  • @WeaselFox : 我想读取一个图像文件并将其转换为字节数组。
  • #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"))) 打印类型(pictureData) profilePictureAdded = soapy.addProfilePicture(auth, 'admin', 'avatar.png', 'image/ png', pictureData) if profilePictureAdded: print "Successfully added new profile picture..." else: print "Failed to add new profile picture..."
  • @WeaselFox 我正在向我的 odoo 模块查找这个问题。我将图像上传到 S3,我想即时创建缩略图,感谢这个问题,我可以:)

标签: python


【解决方案1】:

使用bytearray:

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

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

【讨论】:

  • 顺便说一句。使用可以直接解释数据的图像格式执行此操作更有意义,例如 PNM 系列(PBM、PGM、PPM)。
  • 如何做这个转换的逆向,即将bytearray转成image?
【解决方案2】:

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

import base64

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

Source

【讨论】:

    【解决方案3】:

    这对我有用

    # 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()
    

    【讨论】:

    • 你返回什么? - 没有定义函数
    • @Ghoul Fool 我从原始函数中复制了它。更新了答案以删除 return 语句。谢谢
    【解决方案4】:
    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 中的剪贴板。

    【讨论】:

    • 所以 BytesIO() 来自 io 包 (io.BytesIO())。我尝试了这段代码,但它给了我错误 AttributeError: exit
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 2013-05-19
    • 2018-11-30
    • 2013-01-14
    • 2013-07-29
    相关资源
    最近更新 更多