2016-06-07 30 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 
     } 
    });