Python Script to convert Image into Byte array

前端 未结 4 586
予麋鹿
予麋鹿 2020-12-08 06:36

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.

相关标签:
4条回答
  • 2020-12-08 06:56

    Use bytearray:

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

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

    0 讨论(0)
  • 2020-12-08 06:56
    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.

    0 讨论(0)
  • 2020-12-08 07:11

    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
    
    0 讨论(0)
  • 2020-12-08 07:14

    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

    0 讨论(0)
提交回复
热议问题