webcam

As the regular readers of tricksmode know that I am pursuing engineering in Information Technology and a part time blogger. Some day ago, I had to finish a project in java which involves input from webcam or you can say that we have to capture images from webcam. The task was little bit complicated because me and mine team partners don’t know anything about hardware interaction in java. But with the help of some open source java libraries we finished up our task without facing much problems.
The main problem which we faced during implementing libraries is that, The libraries didn’t came with proper getting started documentation, We also searched google on the same but didn’t got any positive response.
So today we are sharing a java swings program to capture webcam images and some essential libraries to implement that program on your machine.

Things Required:

1) Java installed on your computer.
2) An usb camera or webcam.
3) Net beans installed on your computer.
4) LTI-CIVIL java library.

What is an LTI-CIVIL library?

LTI-CIVIL is an open source java library for capturing images from webcam or usb camera. The best thing about this library is that, it doesn’t depend on JMF (Java Media Framework) and works well on windows, Linux and Mac os.

How to configure/implement LTI-CIVIL library to use it with my project?

If you are using net beans then LTI-CIVIL library are very easy to configurable. We just have to set some jar files and dll files and we are done. Just a minute we are showing it step by step.

Here we start,

How To Capture Webcam Images In Java Swings With LTI-CIVIL Library

1) Install java and net beans if you haven’t installed them yet.

2) Open net beans and create a new java project.

new project netbeans

3) Now right click on your newly created project and create a new java class and name that “TestWebCam” without quotes.

create java class

4) Now copy and paste the following code in TestWebCam.java class.

/*Start copying from here*/
import com.lti.civil.CaptureDeviceInfo;

 

import com.lti.civil.CaptureException;

 

import com.lti.civil.CaptureObserver; 

import com.lti.civil.CaptureStream; 

import com.lti.civil.CaptureSystem; 

import com.lti.civil.CaptureSystemFactory; 

import com.lti.civil.DefaultCaptureSystemFactorySingleton; 

import com.lti.civil.Image; 

import com.lti.civil.awt.AWTImageConverter; 

import com.sun.image.codec.jpeg.JPEGCodec; 

import com.sun.image.codec.jpeg.JPEGImageEncoder; 

import java.awt.event.ActionEvent; 

import java.awt.event.ActionListener; 

import java.awt.image.BufferedImage; 

import java.io.ByteArrayInputStream; 

import java.io.ByteArrayOutputStream; 

import java.io.File; 

import java.io.FileOutputStream; 

import java.io.IOException; 

import java.util.Calendar; 

import java.util.List; 

import javax.imageio.ImageIO; 

import javax.swing.ImageIcon; 

import javax.swing.JButton; 

import javax.swing.JFrame; 

import javax.swing.JPanel; 

import javax.swing.WindowConstants; 

public class TestWebCam implements CaptureObserver { 

JButton start = null; 

JButton shot = null; 

JButton stop = null; 

CaptureStream captureStream = null; 

boolean takeShot=false; 

public TestWebCam() { 

CaptureSystemFactory factory = DefaultCaptureSystemFactorySingleton.instance(); 

CaptureSystem system; 

try { 

system = factory.createCaptureSystem(); 

system.init(); 

List list = system.getCaptureDeviceInfoList(); 

int i = 0; 

if (i < list.size()) { 

CaptureDeviceInfo info = (CaptureDeviceInfo) list.get(i); 

System.out.println((new StringBuilder()).append(“Device ID “).append(i).append(“: “).append(info.getDeviceID()).toString()); 

System.out.println((new StringBuilder()).append(“Description “).append(i).append(“: “).append(info.getDescription()).toString()); 

captureStream = system.openCaptureDeviceStream(info.getDeviceID()); 

captureStream.setObserver(TestWebCam.this); 

} 

} catch (CaptureException ex) { 

ex.printStackTrace(); 

} 

//UI work of the program 

JFrame frame = new JFrame(); 

frame.setSize(7000, 800); 

JPanel panel = new JPanel(); 

frame.setContentPane(panel); 

frame.setVisible(true); 

frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); 

start = new JButton(“Start”); 

stop = new JButton(“Stop”); 

shot = new JButton(“Shot”); 

panel.add(start); 

panel.add(stop); 

panel.add(shot); 

panel.revalidate(); 

start.addActionListener(new ActionListener() { 

public void actionPerformed(ActionEvent e) { 

try { 

captureStream.start(); 

} catch (CaptureException ex) { 

ex.printStackTrace(); 

} 

} 

}); 

stop.addActionListener(new ActionListener() { 

public void actionPerformed(ActionEvent e) { 

try { 

captureStream.stop(); 

} catch (CaptureException ex) { 

ex.printStackTrace(); 

} 

} 

}); 

shot.addActionListener(new ActionListener() { 

public void actionPerformed(ActionEvent e) { 

takeShot=true; 

} 

}); 

} 

    public void onNewImage(CaptureStream stream, Image image)  { 

        

if(!takeShot) return; 

takeShot=false; 

System.out.println(“New Image Captured”); 

byte bytes[] = null; 

try { 

if (image == null) { 

bytes = null; 

return; 

} 

try { 

ByteArrayOutputStream os = new ByteArrayOutputStream(); 

JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(os); 

jpeg.encode(AWTImageConverter.toBufferedImage(image)); 

os.close(); 

bytes = os.toByteArray(); 

} catch (IOException e) { 

e.printStackTrace(); 

bytes = null; 

} catch (Throwable t) { 

t.printStackTrace(); 

bytes = null; 

} 

if (bytes == null) { 

return; 

} 

ByteArrayInputStream is = new ByteArrayInputStream(bytes); 

File file = new File(“/img” + Calendar.getInstance().getTimeInMillis() + “.jpg”); 

FileOutputStream fos = new FileOutputStream(file); 

fos.write(bytes); 

fos.close(); 

BufferedImage myImage = ImageIO.read(file); 

shot.setText(“”); 

shot.setIcon(new ImageIcon(myImage)); 

shot.revalidate(); 

} catch (IOException ex) { 

ex.printStackTrace(); 

} 

} 

    public void onError(CaptureStream arg0, CaptureException arg1) { 

        throw new UnsupportedOperationException(“Error is coming “); 

       

    } 

public static void main(String args[]) 

throws Exception { 

TestWebCam test = new TestWebCam(); 

}
}
/*Code Ends here*/
5) you will see a lot of errors are coming in code, don’t worry, this is because we didn’t configured LTI-CIVIL libraries yet. To Configure LTI-CIVIL libraries first of all go to this link and download the LTI-CIVIL libraries.

6) Unzip the downloaded folder to desktop.

7) Open the downloaded folder you will see a folder named “native
Open “Native” Folder and Select your operating system. If you are developing a java swings webcam capture program for windows then open win32 folder. If you are using linux then, Open Linux-amd64 or X86 based on your machine configuration. And mac users open macosx universal folder.

native folder in LTI-CIVIL8) Now copy all the contents of the selected folder and paste them your netbeans project folder. For windows users netbeans project folder exists at Documents > NetbeansProjects>Project Name

For windows users, If your project name is “JavaApplication1”, Then go to documents>NetbeansProjects>JavaApplication1 and Paste the copied contents there.

9) Now open Netbeans and right click on your project, Then Go to properties and then select “libraries” from the right panel. Now click on “Compile” tab and then finally click on Add JAR/FOLDER. After that Browse to the LTI-CIVIL folder which we had downloaded earlier. And add these 4 Jar files lti-civil.jar, lti-civil-no_s_w_t.jar , lti-civil-noswt.jar , lti-civil-noutils.jar to your project.

Adding the jar files to a project

10) Once you had done, you will see that all errors are gone, and the java swings program is properly capturing images from webcam.Snapshot of Java Webcam Image Capturing Program using LTI-CIVIL
Java swing program to capture webcam imagesI tried my best to make this article as simple as I can, if you are facing any problem while implementing LTI-CIVIL or this webcam capture program on your computer, Kindly Comment below and give us a chance to help you.

He is Founder and Editor-in-Chief of Tricksmode.com He is a 24 year guy from Dehradun, India and writes about Blogging, Technology, Mobiles, Gadgets, Softwares etc. For any feedback and queries, mail us to : 3dartistrawat@gmail.com

86 COMMENTS

  1. good afternoon

    the tutorial seems very good, but I have a problem starting the program and click on the start button does not show me usb camera image, and shot precionar button I get the following error:

    New Image Captured

    java.io.FileNotFoundException: \ img1364492550331.jpg (Access Denied)

    at java.io.FileOutputStream.open (Native Method)

    at java.io.FileOutputStream. (FileOutputStream.java: 179)

    at java.io.FileOutputStream. (FileOutputStream.java: 131)

    at TestWebCam.onNewImage (TestWebCam.java: 135)

    I fix the problem

    thanks in advance

  2. Start button is used to initiliaize webcam/usb camera….After clicking on start button we have to click on shot button to take a picture from webcam to java swing panel..
    Now onwards after you run this program just follow a small sequence..
    Start>Shot>Stop …Let me inform what will happen next..?

  3. pressed the start button and then shot and apaerece me this error

    java.io.FileNotFoundException: \ img1364512374173.jpg (Access Denied)

    at java.io.FileOutputStream.open (Native Method)

    at java.io.FileOutputStream. (FileOutputStream.java: 179)

    at java.io.FileOutputStream. (FileOutputStream.java: 131)

    at TestWebCam.onNewImage (TestWebCam.java: 135)

  4. I also tested the same program on my windows 7 machine…and working quite good…But i think you are facing this problem beacause your classpath is not set..or there may be some problem while searching your webcam drivers…If this is happening because of classpath then Follow 7,8,9 Steps carefully..

  5. Hi

    I am having a problem with the program for imports, giving me error:
    com.sun.image.codec.jpeg.JPEGCodec
    com.sun.image.codec.jpeg.JPEGImageEncoder

    These are not recognized in Java giving me the error in the code from the imports:
    JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(os);
    jpeg.encode(AWTImageConverter.toBufferedImage(image));

    Is there a way to solve this as do not know how to?

  6. Hi… it seems i encountered the same problem but i successfully test sample capture by replacing some code on this line

    File file = new File(“/img” + Calendar.getInstance().getTimeInMillis() + “.jpg”);

    change it to for example you create a folder images on you project folder

    File file = new File(“images/”);

  7. It looks like you didn’t configured the project properly..
    This error is coming because of class path for .jar files is not setup yet..
    To setup class path, Just follow 9th step, And error will disappear automatically..

  8. java.lang.ExceptionInInitializerError

    Caused by: java.lang.RuntimeException: Uncompilable source code – class TestWebCam is public, should be declared in a file named TestWebCam.java

    at TestWebCam.(NewClass.java:100)

    Exception in thread “main” Java Result: 1

    this is a error

  9. Hi Aman, I am getting the following exception:

    EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000000006d9d7fd5, pid=3944, tid=7992

    when trying to fetch the lust below

    system.init();

    List list = system.getCaptureDeviceInfoList();

    Please advice. Thanks.

  10. EXCEPTION_ACCESS_VIOLATION mostly occurs with windows 7 and windows vista operating systems..

    This issue could be seen due to User Account Control (UAC) feature enabled on windows 7 operating system..
    UAC is enabled by default in Windows Vista and Windows 7, as a result, we might encounter some compatibility problems

    Temporarily disabling UAC may resolve the exception access issue,

  11. Hey.. Thanku so much for this post
    this is very helpful..
    now i am able to capture images from webcam.. 🙂
    In a addition to this..
    can u plz tell me the procedure of capturing video/image from ip camera..

    looking frwd for ur rply.. pls rply ASAP

  12. hi, Why I have a com.lti.civil.CaptureException: java.lang.UnsatisfiedLinkError: no civil in java.library.path

    error?

  13. Hi Aman,

    I followed the instructions, but the GUI window does not come up after I hit the run button. There were no errors in the program, and the build was successful. I used Netbeans IDE 6.7.1 along with JDK6. I previously tried this in Eclipse with JDK 7 and got some errors with the JPEGCodec. I then switched to Netbeans version 6 with JDK 6. I would like to know why my GUI window does not show up in Netbeans and what I need to do to get it to show up so that I can take pictures.

    Thanks,

    -Bernard

  14. Hi i have à new error efter this, can’t load IA 32 bit.dll to à and 64 bits plattform, but efter i choose jdk 32 bits, it still gives me same problem, do u know how to Solve That?

  15. I am using Windows 7. My webcam is a Logitech webcam C250. I also have an HP webcam that came installed with my laptop. I know both devices are working because I have used them to take other pictures. I just haven’t been able to take pictures with either webcam using a java program.

  16. I think you are running the program on 32 bits operating system..for better results..try running it on 64 bit operating system..it would be best if you use windows 7 [64 bit] operating system

  17. hi,
    my error is “java.lang.UnsatisfiedLinkError: C:\Users\ayda\Documents\NetBeansProjects\JavaApplication1\civil.dll: Can’t load IA 32-bit .dll on a AMD 64-bit platform”. plz help me.

  18. i m using win 7.i got the error “java.lang.UnsatisfiedLinkError: C:\Users\ayda\Documents\NetBeansProjects\JavaApplication1\civil.dll: Can’t load IA 32-bit .dll on a AMD 64-bit platform”

  19. bro i tried your trick to capture image through webcam and as i include all the jar files all error are gone bt while m running my page i found lots of run tym error plz help me dude …..i can see three button start stop and shot bt its nt working …

  20. bro its working thankz….dude i am working on face detection project and i want to store the images in sql database in the form of byte is it possible that after storing the image in the form of bytes to compare dat stored image wid d moving image its really goin very difficult for me plz suggest me sumthing…..

  21. its little bit complicated to compare a static image with dynamic image..I think you are doing it in wrong way..just apply some java object tracking concepts in your project and you can do this task more easily..
    and one more thing don’t store the whole image in database..it will make your db very large..just store the parts of image which you needs really..you can do this by object tracking in java..

  22. no dude u didnt got my point i am saving the image in the form of byte bt when m goin to compare dat image with moving image its byte changes nd it does nt detect the image is it possible to save 10 or 20 snap of a single image so dat at the time of comparison it will detect the image……is it possible through open cv…

    bro i dun knw much about object tracking bt if we apply object object tracking in our project den is it goin to detect a dynamic image….cn u plz xpain about this concept of object tracking….

  23. dude

    dude can u plz xpalin hw to implement object trackind do u hv any coding related to object tracking

  24. i have problem

    com.lti.civil.CaptureException: java.lang.UnsatisfiedLinkError: C:\Users\Blue\Documents\NetBeansProjects\JavaApplication1\civil.dll: Can’t load IA 32-bit .dll on a AMD 64-bit platform
    at com.lti.civil.impl.jni.NativeCaptureSystemFactory.createCaptureSystem(NativeCaptureSystemFactory.java:24)
    at TestWebCam.(TestWebCam.java:40)
    at TestWebCam.main(TestWebCam.java:141)
    Caused by: java.lang.UnsatisfiedLinkError: C:\Users\Blue\Documents\NetBeansProjects\JavaApplication1\civil.dll: Can’t load IA 32-bit .dll on a AMD 64-bit platform
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary1(ClassLoader.java:1939)
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1864)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1854)
    at java.lang.Runtime.loadLibrary0(Runtime.java:845)
    at java.lang.System.loadLibrary(System.java:1084)
    at com.lti.civil.impl.jni.NativeCaptureSystemFactory.createCaptureSystem(NativeCaptureSystemFactory.java:21)
    … 2 more

  25. thanks for the answer, but I think that you don’t underestood what I mean. When I clik start the cam start start working but I don’t see what it capt, only after cliking shoot I see picture, I want to know if can I see what the cam capt before cliking shoot. I hope that you underestand me.

  26. Yes you can see the image before taking a shot..

    First Click on start button: It will start your webcam..and show you the live images coming from your webcam.

    Then click on Shot button: It will take the shot of your picture coming from webcam..

    To select different images, Just click on image..

  27. Hi friend I am using your code and it is working perfectly. But can we show a video image on the label while we click on Start Button (Like it shows in mobile phones) so that user can set his image properly and capture the image while clicking on Shot Button.

  28. Nice question bibin, But i think LTI-civil doesn’t support this…You can use Java Media Framework for that purpose..else you have to modify the coding of LTI-Civil so you can show that on java swings panel.

  29. Thanks Aman, I have achieved that by doing some changes in code.

    Next problem I am facing on these two imports

    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;

    Because Java 7 does not support com.sun package, so is there any replacement for

    JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(os);
    jpeg.encode(AWTImageConverter.toBufferedImage(image));

    these two lines.

  30. off course there is solution..but you have to apply it by yourself..as in above comment @Bibin Mathew did..
    The coding that i had provided is very basic coding to access webcam with java and capture an image with it…Just edit the coding of as you want…and you will be done..

  31. thanks but am getting the following exception on taking shots.

    java.io.FileNotFoundException: \img1369377453709.jpg (Access is denied)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.(FileOutputStream.java:212)
    at java.io.FileOutputStream.(FileOutputStream.java:165)
    at TestWebCam.onNewImage(TestWebCam.java:133)

  32. Hello Dilini,
    This error is coming because you didn’t pasted the LTI-CIVIL native folder files to net beans project folder correctly..as i suggested to others try following 7th and 8th steps carefully..and you will be done..

  33. Hello Roy, Yes we can’t use LTI civil on 64 bit windows machine..but its possible to use it on 64 bit Linux machine..
    You can check LTI-CIVIL official website for more information..

  34. I am also facing same problem I am using Windows 7. I also have webcam that came installed with my laptop. After press Start button, I am unable to see live image from webcam. Please provde me solution

    Thanks & Regards
    Rakesh

  35. HI Aman ,
    The above code works fine for me . But i want to capture a running object automatically through java code . Is there Any api with recognize the running object in front of camera and take a shot of that object .

  36. If your windows version is 32 bit then make sure you are following the steps carefully, Most of the peoples are not following 7th,8th and 9th step properly thats why facing this problem..

  37. Hello Harsh, If you want to do it manually then you have to implement some java object tracking concept in it..
    If you want to use API then Java Motion Tracking API would be good for you..else you can search on Google..you will get hundreds there..

  38. Hi…I have a problem ……Like>>> FERLEY GALLEGO…

    I have 4 Device to detect my computer….

    and when i’m fixed the Device Like this>> CaptureDeviceInfo info = (CaptureDeviceInfo) list.get(3);

    list.get(3) = USB Camera;

    and then I’m click on the start button

    No Exception or an Error in my console

    but Other button can not click
    …..I don’t know why?

    I’m newbies in Media processing…..

    Advice me Pls….Thanks

  39. Thanks.. It helped so lot, I want another help.. I wanna display in panel that, to where my camera focusing b4(after) capturing. So that i can capture image of object(anything) of interest. Can u tell me how to do it…?.plz..

  40. after running the project
    it shows three buttons only “start stop and shot.”
    after clicking start my webcam is on but m not able to see any picture and after clicking shot button
    there is nothing happening and the console is showing this error.

    New Image Captured

    java.io.FileNotFoundException: \img1372543999588.jpg (Access is denied)

    at java.io.FileOutputStream.open(Native Method)

    at java.io.FileOutputStream.(FileOutputStream.java:212)

    at java.io.FileOutputStream.(FileOutputStream.java:165)

    at testwebcam.TestWebCam.onNewImage(TestWebCam.java:130)

    please help me in fixing it.

  41. Device ID 0: \\?\usb#vid_046d&pid_092f#5&5f39f41&0&1#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\{9b365890-165f-11d0-a195-0020afd156e4}

    Description 0: Logitech QuickCam Express/Go

    New Image Captured

    java.io.FileNotFoundException: \img1373575309102.jpg (Access is denied)

    at java.io.FileOutputStream.open(Native Method)

    at java.io.FileOutputStream.(Unknown Source)

    at java.io.FileOutputStream.(Unknown Source)

    at TestWebCam.onNewImage(TestWebCam.java:130)

    Java_com_lti_civil_impl_jni_NativeCaptureStream_stop, stopping…

    DSCaptureStream::stop, stopping…

    DSCaptureStream::stop, stopped.

    Java_com_lti_civil_impl_jni_NativeCaptureStream_stop, stopped.

    Please tell me what to do……..

  42. hello Rishabh you are not following the mentioned steps properly..
    if you will add jar and paste contents in net beans directory than there will be no error like this..

  43. i have done exactly what you have said in the tutorial….. and not only me my 3 friends are also facing the same problem….. pls give a fast solution because it is a very important part of my project…..

  44. Good day sir, thanks for posting this online for us am really really greatfull for this.
    I have being  able to download all necessary files and added all necessary libraries to the project and it is without any errors, the issue i have with it sir is that each time i run the project it shows the interface and when i click the start button the project simply hangs and it says “Java (TM) Platform SE binary has stopped working”
    Please what could cause this and how do i resolve the issue

  45. sir actually the tutorial is wonderful but after done with all step carefully i still got some errors n not able to run the code successfully

    errors like (illegal character: 8220

    not a statement

    illegal character: 8221

    not a statement

    illegal character: 8220

    not a statement

    illegal character: 8221) are coming n there are many more other errors plzzzzzzzz help me out this prob…..
    thank you

  46. thanks very much for your helpful code but am facing a problem,when i click shot,it shows me an image written “WEBCAM MAX” and not my image,please help me on this

  47. Hello Sir ,
    Thanks for your code. But i am unable to start my webcam as i press the start button.
    Could you please help me on this.
    Thanks.

  48. I am getting this error when I run the program and am unable to see the image from the webcam on my screen. Please help.

    Device ID 0: \\?\usb#vid_0c45&pid_6340&mi_00#6&5a6bd31&0&0000#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\global
    Description 0: USB Camera
    New Image Captured
    java.io.FileNotFoundException: \img1484734619481.jpg (Access is denied)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.(FileOutputStream.java:213)
    at java.io.FileOutputStream.(FileOutputStream.java:162)
    at javaapplication4.TestWebCam.onNewImage(TestWebCam.java:131)
    Java_com_lti_civil_impl_jni_NativeCaptureStream_stop, stopping…
    DSCaptureStream::stop, stopping…
    DSCaptureStream::stop, stopped.
    Java_com_lti_civil_impl_jni_NativeCaptureStream_stop, stopped.

LEAVE A REPLY

CommentLuv badge