How to pass an image to a subprocess in python
<p>The program is trying to read an image and then trying to pass the image to one of the subprocess for further preprocessing. I am trying to pass the image using subprocess args parameter.</p>

<pre><code>import subprocess
import base64

img =[]
img.append(base64.b64encode(open('test.jpg', "rb").read()))
output = subprocess.check_output(['python', 'test1.py',img])
print "output",output
</code></pre>

<p>In the code the image is being passed to test1.py, In test1.py i am  manipulating the image and then trying to return it back to the main process.</p>

<p>The current implementation is giving an error :
    <strong>The filename or extension is too long</strong></p>

<p>so how can i pass this image from the main process to the subprocess and also how can i send back the image back from the subprocess to the main process?</p>

<p>I do it by using the <code>subprocess.Popen</code>ï¼</p>

<p>This is my directory structure:</p>

<pre><code>.
âââ main.py
âââ src.jpg
âââ test1.py
</code></pre>

<p>In the following code, I change the size of the src.jpg and save it as a new file called <code>src.thumbnail</code>.</p>

<p>This is the <code>main.py</code>. In the <code>main.py</code> I open two files as input stream(the stream of the original picture) and output stream(the stream of the target picture).</p>

<pre><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import subprocess

def main():
    # args are python interpreter and python file
    args = ["/home/yundongx/.virtualenvs/read/bin/python", "/tmp/img/test1.py"]
    with open("src.thumbnail", "w+b") as outstream, \
                        open("src.jpg", "rb") as instream:
        ps = subprocess.Popen(args, stdin=instream, stdout=outstream)
        ps.wait()


if __name__ == '__main__':
    main()
</code></pre>

<p>And this is the <code>test1.py</code></p>

<pre><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from PIL import Image
import sys
import io

size = (128, 128)

def main():
    try:
        im = Image.open(io.BytesIO(sys.stdin.buffer.read()))
        im.thumbnail(size)
        output = io.BytesIO()
        im.save(output, "JPEG")
        sys.stdout.buffer.write(output.getvalue())
    except IOError as e:
        sys.stderr.write("Cannot read the data\n")
        raise e

if __name__ == '__main__':
    main()
</code></pre>

<p>In the <code>test1.py</code>, The program read the img data from the stdin(you need to convert it to the BytesIO), write the img data(Saved into the BytesIO) to the stdout after processing it.</p>

python image-processing subprocess