Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Script to convert Image into Byte array

Tags:

python

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')
like image 579
Akash Bhardwaj Avatar asked Mar 12 '14 12:03

Akash Bhardwaj


People also ask

How can I get byte array from image?

Read the image using the read() method of the ImageIO class. Create a ByteArrayOutputStream object. Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class. Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.

How do I turn an image into a byte?

Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor. Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter). Finally, Write the image to using the write() method of the ImageIo class.


4 Answers

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.

like image 73
Thomas Baruchel Avatar answered Oct 10 '22 17:10

Thomas Baruchel


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

like image 23
cptPH Avatar answered Oct 10 '22 18:10

cptPH


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()
like image 19
Rami Alloush Avatar answered Oct 10 '22 18:10

Rami Alloush


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.

like image 6
perillaseed Avatar answered Oct 10 '22 16:10

perillaseed