2016-06-07 31 views
0

我无法将从base64编码的图像从python子进程发送到节点。从python子进程接收图像到节点,base64编码

我想:

  • 菌种在节点中的子进程来运行Python文件
  • 开放蟒蛇
  • 旋转图像
  • 编码图像
  • 返回图像编码的字符串通过标准输出到节点
  • 接收节点中的编码字符串并将其写入图像文件。

蟒蛇文件很简单:

import sys 
from PIL import Image 
import base64 
import os 

### Get image 
inputFilePath = sys.argv[1] 
img = Image.open(inputFilePath) 

### Operate on image 
img = img.rotate(180) 

### Save image 
img.save('temp_image.jpg') 

### Convert image to base64 
with open('temp_image.jpg','rb') as imageFile: 
    encodedString = base64.b64encode(imageFile.read()) 

    ### Remove Temp file 
    os.remove('temp_image.jpg') 

    ### send the base64 string to parent process 
    print(encodedString) 

这应该编码的图像发送到父进程。

在节点中,我试图将编码的字符串写入图像文件。

var spawn = child.spawn(cmd, args); 

var chunk = '' 
spawn.stdout.on('data', function(data){ 
    chunk += data.toString(); 
}); 

spawn.stdout.on('close', function(data){ 
    fs.writeFile(destination, chunk, 'base64', function(err){ 
     console.log("err: " + err) 
    }); 
    }); 
    console.log("Done"); 
}); 

我的问题:该文件太小/否则损坏。我不太清楚如何解决它 - 任何帮助将不胜感激!

+0

可能值得检查['gm'](https://github.com/aheckmann/gm)之类的替代方法直接从Node执行此操作。 – robertklep

回答

0

为什么要chunk + = data.toString()?

您收到的数据已经是字符串了,根据您的python代码,您将整个打印图像,所以您不需要chunk + =任何东西。

只需将stdout写入到nodejs端的文件中即可。

此外,您可以尝试使用childProcess.exec,如果产卵不起作用。确保查看NodeJS API文档。

//or var or const 
    let childProcess = require('child_process'); 

    childProcess.exec('python interface.py', function(error, stdout, stderr) { 
     if (error !== null) { 
      console.log(`exec error: ${error}`); 
      //and handle the child process error maybe? 
     } 
     try { 
      do.something.with.your.stdout() // replace this line with real code 
     } 
     catch (e) { 
      // handle your error 
     } 
    });