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();
 }
}
asked May 9, 2017 at 8:13
3
  • Possible duplicate of read the output from java exec Commented May 9, 2017 at 8: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ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿ ... Commented May 9, 2017 at 8:39
  • It doesnt work. Commented May 9, 2017 at 8:52

1 Answer 1

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();
 }
}
answered May 11, 2017 at 7:44
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.