59

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.

#!/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')
4
  • 2
    why would you want that? how would that help you to upload? theres not enough data for a meaningful answer Commented Mar 12, 2014 at 12:18
  • @WeaselFox : I want to read an Image file and convert it into Byte array. Commented Mar 12, 2014 at 12:27
  • 2
    #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"))) print type(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..." Commented Mar 12, 2014 at 12:32
  • @WeaselFox I was looking this question to my odoo module. I upload an image to an S3 and I wanted to create a thumbnail on the fly, thanks to this question I can :) Commented Jun 23, 2020 at 4:07

5 Answers 5

94

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.

Sign up to request clarification or add additional context in comments.

3 Comments

BTW. It is more meaningful to do that with image formats where you can directly interpret the data, which is the case for instance with the PNM family (PBM, PGM, PPM).
How to do the reverse of this conversion, i.e. converting bytearray to image?
I like it because it is the most basic, I have a shortage of rb
21

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

2 Comments

What are you returning? - there's no function defined
@Ghoul Fool I copied it from my original function .. updated the answer to remove the return statement. Thanks
16

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

1 Comment

What's the best way to decode it, let's say into a PNG file??
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:]

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

1 Comment

So BytesIO() is from the io package (io.BytesIO()). I tried this code but it gave me the error AttributeError: exit
0
#!/usr/bin/env python
#__usage__ = "To Convert Image pixel data to readable bytes"

import numpy as np
import cv2
from cv2 import *

class Image2ByteConverter(object):

    def loadImage(self):
        # Load image as string from file/database
        file = open('Aiming_ECU_Image.png', "rb")
        return file

    def convertImage2Byte(self):
        file = self.loadImage()
        pixel_data = np.fromfile(file, dtype=np.uint8)
        return pixel_data

    def printData(self):
        final_data = self.convertImage2Byte()
        pixel_count = 0
        for data in final_data:
            pixel_count += 1
            print("Byte ", pixel_count,": ", int(data))

    def run(self):
        # self.loadImage()
        # self.convertImage2Byte()
        self.printData()

if __name__ == "__main__":
    Image2ByteConverter().run()

This Worked for me.

Pre-requisites:

python -m pip install opencv-python
python -m pip install numpy

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.