从 Java 执行扫描图像命令



我正在尝试从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();
    }
}

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

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

最新更新