'Python decoding image spawned by Node.js gives `TypeError: memoryview: a bytes-like object is required, not 'str'`

I'm trying to decode and save an image file passed to a python script.

The image file is read by a Node.JS script index.js and its data passed as image inside a JSON string {"image":readImageFile(), "name":"image.png"}.

The JSON string is received by a spawned Python script script.py.

The problem is when I try to decode the image data, I get the error TypeError: memoryview: a bytes-like object is required, not 'str'.

I tried converting the image data to bytes like base64.decodebytes(bytes(params['image'],'utf-8')) but got the error UnicodeEncodeError: 'utf-8' codec can't encode character '\udc8f' in position 66: surrogates not allowed.

How do I rightly decode the image binary data so I can save it as a file?

Could you please help me spot the problem?

Thanks in advance!

script.py:


import sys, json
import base64

json_str = input() # Capture input

params = json.loads(json_str) # parse input

fileName = params['name'] # Capture file name
fileData = base64.decodebytes(params['image']) # decode image

...
...

print("Image Saved!")
sys.stdout.flush()

index.js:


const spawn = require("child_process").spawn;
const fs = require('fs');

let params = {
    "image":readImageFile(),
    "name":"image.png"
  }

const pyProcess = spawn('py',['script.py']);

pyProcess.stdin.write(JSON.stringify(params) + '\n');

pyProcess.stdout.on("data", (data) =>{
  console.log(data.toString());
});

function readImageFile() {
    try { 
        return fs.readFileSync('color.png',  'binary');
    }
    catch (err) { 
        return err;
    }
}



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source