Multiple Pictures in bytes

Viewed 149

i am trying to save multiple Pictures in one Bytes object from BytesIO. And later on acces these Pictures again from bytes to Picture. But i certainly don't know much about bytes. Is there a way to put something after one Picture in to the Buffer that it later knows where the Picture ends? Client Side:

#cv2 Capture Frame
ret, frame = cls.__cap.read()
buf = BytesIO()
for i in range(10):
    Image.fromarray(frame).save(buf, format='JPEG')
    # Here the Logic for differentiating Pictures
body = buf.getvalue()
requests.post(url,data=body,headers={'content-type': 'application/x-image'})

Website Side:

images_as_bytes = BytesIO(flask.request.data)
for i in range(10):
    # Here the Logic for differentiating Pictures
    img = Image.open(images_as_bytes)
    frame = np.asarray(img)
    # process
1 Answers

I am not sure about the rationale or validity of what you are doing, but you could maybe leverage the fact that all JPEGs end with the EOI marker which is:

0xff 0xd9

And they start with the SOI marker which is:

0xff 0xd8

Similarly, PNG images begin with:

0x89 0x50 0x4e 0x47 0x0d 0x0a 0x1a 0x0a

and end with:

0x49 0x45 0x4e 0x44 0xae 0x42 0x60 0x82

Here is some completely untested, somewhat related code to give you an idea of how to split 2 concatenated PNG images:

#!/usr/bin/env python3

import mmap
import re

pattern = re.compile(rb'(\x89PNG\x0d\x0a\x1a\x0a.*?\x00\x00\x00\x00IEND\xAE\x42\x60\x82)', re.MULTILINE|re.DOTALL)

# I guess we could do 2 TIFFs just as easily, or JPEGs
with open('TwoConcatenatedPNGs.png', 'rb') as f:
    with mmap.mmap(f.fileno(), 0,
                   access=mmap.ACCESS_READ) as m:
        i = pattern.finditer(m)
        for p in i:
         print(p.span())

Create the test file like this:

cat IMAGE1.PNG IMAGE2.PNG > TwoConcatenatedPNGs.png

Best links for understanding Python regex and mmap.

Related