首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Java执行扫描图像命令

从Java执行扫描图像命令
EN

Stack Overflow用户
提问于 2017-05-09 08:13:29
回答 1查看 149关注 0票数 1

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

代码语言:javascript
复制
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();
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-11 07:44:55

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

代码语言:javascript
复制
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();
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43864531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档