【问题标题】:Executing scanimage command from Java从 Java 执行 scanimage 命令
【发布时间】:2017-10-07 10:51:56
【问题描述】:

我正在尝试从 java 运行 scanimage 命令。命令已成功执行,但我无法读取从命令返回的图像。我想从终端读取图像并通过 Java 将其转换为 base64 字符串。我的代码:

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();
    }
}

【问题讨论】:

  • 是的,我可以将行读取为字符串,但我不知道如何转换为 base64。我不知道返回哪种数据类型。它返回304DNpï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿ ...
  • 它不起作用。

标签: java command base64 exec


【解决方案1】:

最后我解决了我的问题。也许其他人需要答案。这是我的解决方案

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();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-23
    • 2013-08-25
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多