2017-05-09 96 views
0

我想從java運行scanimage命令。命令成功執行但我無法讀取從命令返回的圖像。我想從終端讀取圖像,並通過Java將其轉換爲base64字符串。我的代碼:執行從Java的scanimage命令

public String getimagefromscanner(String device) 
{ 
    try { 
     Process p = Runtime.getRuntime().exec("scanimage --resolution=300 -l 0 -t 0 -y 297 -x 210 --device-name " + device); 
     BufferedInputStream input = new BufferedInputStream(p.getInputStream()); 
     byte[] file = new byte[input.available()]; 
     input.read(file); 
     String result = new String(Base64.getDecoder().decode(file)); 
     p.waitFor(); 
     p.destroy(); 
     return result; 
    } catch (IOException e) { 
     return e.getLocalizedMessage(); 
    } catch (InterruptedException e) { 
     return e.getLocalizedMessage(); 
    } 
} 
+0

的可能的複製(http://stackoverflow.com/questions/8149828/read-the-output-from-java-exec) –

+0

是的,我可以讀線作爲字符串,但我不知道如何轉換爲base64。我不知道哪個數據類型返回。它返回'304DNpï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï ¿½ï¿...' – Burak

+0

它不起作用。 – Burak

回答

0

Finnaly我解決了我的問題。也許別人需要回答。這裏[閱讀從Java EXEC輸出]我的解決方案

public String getimage(String device) 
{ 
    try{ 
     Process p = Runtime.getRuntime().exec("scanimage --resolution=300 -l 0 -t 0 -y 297 -x 210 --format png --device-name " + device); 
     InputStream in = p.getInputStream(); 
     ByteArrayOutputStream out = new ByteArrayOutputStream(); 
     byte[] buffer = new byte[8*1024]; 
     int bytesRead, totalbytes = 0; 
     while ((bytesRead = in.read(buffer)) != -1) { 
      out.write(buffer, 0, bytesRead); 
     } 
     String result = Base64.getEncoder().encodeToString(out.toByteArray()); 
     out.close(); 
     p.waitFor(); 
     p.destroy(); 
     in.close(); 
     return result; 
    } catch (IOException e) { 
     return e.getLocalizedMessage(); 
    } catch (InterruptedException e) { 
     return e.getLocalizedMessage(); 
    } 
}