1

I am trying to run scanimage command from java. Command is successfully executed but i can't read image that is returned from command. I want to read image from terminal and convert it to base64 string via Java. My code:

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();
    }
}
Burak
  • 186
  • 9
  • Possible duplicate of [read the output from java exec](http://stackoverflow.com/questions/8149828/read-the-output-from-java-exec) – Yosef Weiner May 09 '17 at 08:23
  • Yes i can read line as string but i don't know how to convert to base64. I dont know which data type returns. It returns `304DNpï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿ ...` – Burak May 09 '17 at 08:39
  • It doesnt work. – Burak May 09 '17 at 08:52

1 Answers1

1

Finnaly I solved my problem. Maybe someone else needs answer. Here my solution

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();
    }
}
Burak
  • 186
  • 9