I'm developing a Java app which will take a screen shot, I have 3 monitors in my office, so I want my app to be able to take a screen shot of the display I'm interested in. What it can do now is to take a screen shot of each screen and save the 3 files. But I don't want to get 3 file each time I run my Java app. Therefore I want to know if there is a way to detect from which screen my Java app is run, and only take the screen shot of that screen, but my question got no answer : How to determine in which monitor my Java app is running?
I thought about creating a shortcut of my Java app's jar file on desktop, then set it's property's target to : "C:\Program Files\AdoptOpenJDK\jdk-8.0.222.10-hotspot\bin\javaw.exe" -jar C:\Dir_Screen_Shoter\dist\Screen_Shoter.jar
Then I pinned the shortcut to Windows task bar, looking like this :
But the problem is : no matter from which display [ it shows up on every display ] I clicked it, my app always runs [ opens ] on the center [main ] display, so my question is : is there a way I can run this app on the display I clicked it, and that it can detect which monitor it is running from ?
I thought about something like : shift-click, alt-click or hold down ctrl then click on the app on tack bar, but it won't detect all those, so what is a good solution so when I run the app, it will know which display to take a screen shot, it's easy if my app opens a window and let user choose which monitor to act on, but I do not want that, I just want it to take a screen shot without opening an application window.
I've found some related questions, but none of them answers my question :
Show JFrame in a specific screen in dual monitor configuration
How to detect the current display with Java?
[ I tried this one, but it always show device Id == 1 ]
My app looks like this so far :
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Screen_Shoter extends JPanel
{
static Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
static JFrame frame=new JFrame("Screen_Shoter");
static int W=screenSize.width,H=screenSize.height;
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String Result="Screen_Size : "+W+" x "+H+"\n",Dir_Screenshots="C:/Dir_Screenshots/",Screen_Shot_File_Name=Dir_Screenshots+format.format(new Date()).replace("-","_").replace(" ","_").replace(":","_")+"_.png";
JLabel infoLabel=new JLabel();
public Screen_Shoter() // Get ScreenShots From Multiple Monitors
{
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gDevs=ge.getScreenDevices();
if (!new File(Dir_Screenshots).exists()) new File(Dir_Screenshots).mkdirs();
int defaultScreenIndex=getScreenIndex();
Out("defaultScreenIndex = "+defaultScreenIndex+"\n");
for (GraphicsDevice gDev : gDevs)
{
DisplayMode mode=gDev.getDisplayMode();
Rectangle bounds=gDev.getDefaultConfiguration().getBounds();
Out("[ "+gDev.getIDstring()+" ] Min : ( "+bounds.getMinX()+" , "+bounds.getMinY()+" ) ; Max : ( "+bounds.getMaxX()+" , "+bounds.getMaxY()+" ) W = "+mode.getWidth()+" , H = "+mode.getHeight());
try
{
Robot robot=new Robot();
BufferedImage image=robot.createScreenCapture(new Rectangle((int)bounds.getMinX(),(int)bounds.getMinY(),(int)bounds.getWidth(),(int)bounds.getHeight()));
ImageIO.write(image,"png",new File(Screen_Shot_File_Name.replace(".png",gDev.getIDstring().replace("\\","")+".png")));
}
catch (AWTException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
infoLabel.setFont(new Font("Times New Roman",0,15));
infoLabel.setForeground(new Color(0,0,218));
infoLabel.setText("<html>"+Result.replace("\n","<P>")+"</html>");
add(infoLabel);
}
int getScreenIndex()
{
int myScreenIndex=-1;
GraphicsConfiguration config=frame.getGraphicsConfiguration();
GraphicsDevice myScreen=config.getDevice();
GraphicsEnvironment env=GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] allScreens=env.getScreenDevices();
for (int i=0;i<allScreens.length;i++)
{
if (allScreens[i].equals(myScreen))
{
myScreenIndex=i;
break;
}
}
Out("frame : "+frame.getBounds());
return myScreenIndex;
}
private static void showOnScreen(int screen,Window frame)
{
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gd=ge.getScreenDevices();
GraphicsDevice graphicsDevice;
if (screen>-1 && screen<gd.length) graphicsDevice=gd[screen];
else if (gd.length>0) graphicsDevice=gd[0];
else throw new RuntimeException("No Screens Found");
Rectangle bounds=graphicsDevice.getDefaultConfiguration().getBounds();
int screenWidth=graphicsDevice.getDisplayMode().getWidth();
int screenHeight=graphicsDevice.getDisplayMode().getHeight();
frame.setLocation(bounds.x+(screenWidth-frame.getPreferredSize().width)/2,bounds.y+(screenHeight-frame.getPreferredSize().height)/2);
// frame.setLocation(bounds.x,bounds.y);
frame.setVisible(true);
}
private void out(String message)
{
System.out.print(message);
Result+=message;
}
private void Out(String message)
{
System.out.println(message);
Result+=message+"\n";
}
// Create the GUI and show it. For thread safety, this method should be invoked from the event-dispatching thread.
static void createAndShowGUI()
{
final Screen_Shoter demo=new Screen_Shoter();
frame.add(demo);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setBounds(0,0,600,178);
frame.setLocationRelativeTo(null);
frame.setVisible(true); // For test only
// showOnScreen(0,frame);
}
public static void main(String[] args)
{
// Schedule a job for the event-dispatching thread : creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } });
}
}
Try having your program look for the mouse pointers location and if on that screen take picture when app is clicked
I have a IP camera that uses the RTSP protocol to transmit images, the following code uses gstreamer to connect, pick up those images and show in Swing (works just right).
What I want to do is pick up the frames direct from the Pipeline of gstreamer (not use Swing), so that I can analyze frame by frame the image.
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import org.gstreamer.Element;
import org.gstreamer.Gst;
import org.gstreamer.Pipeline;
import org.gstreamer.State;
import org.gstreamer.swing.VideoComponent;
public class Main {
public static void main(String[] args) throws InterruptedException {
args = Gst.init("PipelineLauncher", args);
final String def = "rtspsrc location=rtsp://192.168.25.160/av0_0 latency=0 ! decodebin ! ffmpegcolorspace name=testp";
final Pipeline pipe = Pipeline.launch(def);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// Create the video component and link it in
VideoComponent videoComponent = new VideoComponent();
Element videosink = videoComponent.getElement();
pipe.add(videosink);
pipe.getElementByName("testp").link(videosink);
pipe.setState(State.PAUSED);
if (pipe.isPlaying()) {
System.out.println("Pipeline playing");
} else {
System.out.println("Pipeline not playing");
}
// Start the pipeline processing
pipe.play();
pipe.setState(State.PLAYING);
if (pipe.isPlaying()) {
System.out.println("Pipeline playing");
} else {
System.out.println("Pipeline not playing");
}
// Now create a JFrame to display the video output
JFrame frame = new JFrame("Swing Video Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(videoComponent, BorderLayout.CENTER);
videoComponent.setPreferredSize(new Dimension(800, 600));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
Gst.main();
pipe.setState(State.NULL);
}
}
I suggest using a pad probe (http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gstreamer/html/GstPad.html#gst-pad-add-probe). It will then trigger a callback with the buffer that is about to go through the pad. So you can put this at the pad you are most interested in in the pipeline (encoded RTP data or uncompressed raw image for example).
If you are just interested in the final data the appsink is also a good place to look at (http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-base-libs/html/gst-plugins-base-libs-appsink.html).
In case of appsink and if you want to display the image and also want the data you may use a tee element (http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gstreamer-plugins/html/gstreamer-plugins-tee.html).
You can use appsink to get the buffers from a pipeline.
http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-base-libs/html/gst-plugins-base-libs-appsink.html
I have recently started learning java.I want to make a game like https://sites.google.com/site/millseagles/home/Games/multiplayer/tron
I have made it in c++ once using a simple graphics lib. I have the graphics part down i plan to use small images and use http://horstmann.com/sjsu/graphics/ this basic graphics lib.I can't figure out keyboard input i want it so if you press an arrow the picture adds a small green square(I have a green.png).I can't figure out to use keyboard listeners.I get all these errors.I just need a simple lib that i can say getKey() or something and i can use if() to figure out the action.this is the code I have.I was messing with the key event but don't understand it.
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.*;
public class game implements KeyListener
{
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
public game()//snake like game
{
}
public void test()
{
int x=30,y=30;//middle total 60x60
tile[] map=new tile[3600];//tile is a class i made that is a picture and some int and bool using the simple lib i linked 60 by 60 tiles
for(int i=0;i<3600;i++)
{
map[i]=new tile();
}
}
public void keyPressed(KeyEvent e)//this does not work i want it to work when a key is clicked
{
while(x>0)//this part works when it is not in the keypressed function
{
map[(y*60)+x].load(4);//4 refrences a green rectangle image
map[(y*60)+x].draw(x,y,10);//draw it based on x and y 10 pixels sized tiles
x--;//make a line going left
}
}
}
I know this may be messy.I have tested my code it works it just breaks when i try to implement keyboard events.If you can point me to a much more beginner friendly lib that would be great.
You simply have to add the listener to something (e.g. the window where the game is being played).
I will give you an example, where we will simply display the code of the key being stroked.
This is the class where you produce the interface:
import java.awt.Dimension;
import javax.swing.JFrame;
public class Game {
public static void main(String[] args) {
/* Creating a window (300x400) */
JFrame frame = new JFrame("Add your own title");
frame.setPreferredSize(new Dimension(300, 400));
/* This is the part where we add the keyListener (notice that I am also sending
* this window as a parameter so that the listener can modify it)*/
frame.addKeyListener(new ArrowListener(frame));
/* Making the window visible */
frame.pack();
frame.setVisible(true);
}
}
And this is the class where we have the listener:
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ArrowListener implements KeyListener {
/* We keep the window as an instance variable so we can modify it once the event is triggered */
JFrame frame;
/* This is the constructor */
public ArrowListener(JFrame j) {
frame = j;
}
/* This is where the magic happens */
public void keyPressed(KeyEvent e) {
/* Modify this with what you actually want it to do */
/* We clear the panel so we can add new text without any other text behind it */
frame.getContentPane().removeAll();
/* We add some text that actually shows the keyCode (left arrow = 37, top = 38, right = 39, bottom = 40) */
frame.add(new JLabel("Key Code #" + String.valueOf(e.getKeyCode())));
/* Redrawing the window */
frame.revalidate();
}
/* These two are part of the contract we made when we decided to
* implement the KeyListener */
public void keyTyped(KeyEvent e) { /* Do nothing */ }
public void keyReleased(KeyEvent e) { /* Do nothing */ }
}
Note: when running the program press the keys to see the text appearing on the window.
I didn't get around the library you were using, but I used the most popular one called swing (tutorial)
Hello i am trying to Create the beginning of a full screen game and i am having issues. I want a blue background with white text and the entire screen to be changed to 800*600. The problem is i get a screen with an 800*600 box in the middle(not visible but i can tell by mouse boundaries) and my background is black.
My Code:
import java.awt.*;
import javax.swing.JFrame;
/**
* Write a description of class Full here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Full extends JFrame
{
public static void main(String[] args){
DisplayMode dm = new DisplayMode(800,600,16, DisplayMode.REFRESH_RATE_UNKNOWN);
Full full = new Full();
full.run(dm);
}
public void run(DisplayMode dm){
setBackground(Color.BLUE);
setForeground(Color.WHITE);
setFont(new Font("Arial", Font.PLAIN,24));
Screen s = new Screen();
try{
s.setFullScreen(dm,this);
try{
Thread.sleep(15000);
}catch(Exception ex){}
}finally{
s.restoreScreen();
}
}
public void paint(Graphics g){
if(g instanceof Graphics2D){
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
}
g.drawString("This is gonna be awesome!!",200,200);
}
}
public class Screen
{
private GraphicsDevice vc;
Window myWindow;
public Screen(){
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
vc = env.getDefaultScreenDevice();
}
public void setFullScreen(DisplayMode dm, JFrame myWindow){
myWindow.setUndecorated(true);
myWindow.setResizable(false);
vc.setFullScreenWindow(myWindow);
if(dm != null && vc.isDisplayChangeSupported()){
try{
vc.setDisplayMode(dm);
}catch(Exception ex){}
}
}
public Window getFullScreenWindow(){
return vc.getFullScreenWindow();
}
public void restoreScreen(){
Window w = vc.getFullScreenWindow();
if(w != null){
w.dispose();
}
vc.setFullScreenWindow(null);
}
}
This is a short answer, because it seems that you are on the wrong trace :)
Games should be using OpenGL or DirectX, so the graphical work is done by the GPU. I strongly recommend OpenGL, since it is compatible with every platform. The way you started, the game will run completely on the CPU, which is not good.
Take a look at LWJGL (LightWeight Java Game Library). It is a cross-platform library that allows you to use OpenGL. It will require some Googling for tutorials, but it is really worth it. Your performance of the game will be a lot better, and your game will be made the way it has to be. Just to give you an idea, Minecraft is made with LWJGL.
OpenGL allows you to make a quick start with your game development, using some simple methods, which is good first a first game experience. Later on, you will find out how to do things more efficient, but that would be too much information to start of with :D
Good luck!
How can I continuously capture images from a webcam?
I want to experiment with object recognition (by maybe using java media framework).
I was thinking of creating two threads
one thread:
Node 1: capture live image
Node 2: save image as "1.jpg"
Node 3: wait 5 seconds
Node 4: repeat...
other thread:
Node 1: wait until image is captured
Node 2: using the "1.jpg" get colors
from every pixle
Node 3: save data in arrays
Node 4: repeat...
This JavaCV implementation works fine.
Code:
import org.bytedeco.javacv.*;
import org.bytedeco.opencv.opencv_core.IplImage;
import java.io.File;
import static org.bytedeco.opencv.global.opencv_core.cvFlip;
import static org.bytedeco.opencv.helper.opencv_imgcodecs.cvSaveImage;
public class Test implements Runnable {
final int INTERVAL = 100;///you may use interval
CanvasFrame canvas = new CanvasFrame("Web Cam");
public Test() {
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
public void run() {
new File("images").mkdir();
FrameGrabber grabber = new OpenCVFrameGrabber(0); // 1 for next camera
OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
IplImage img;
int i = 0;
try {
grabber.start();
while (true) {
Frame frame = grabber.grab();
img = converter.convert(frame);
//the grabbed frame will be flipped, re-flip to make it right
cvFlip(img, img, 1);// l-r = 90_degrees_steps_anti_clockwise
//save
cvSaveImage("images" + File.separator + (i++) + "-aa.jpg", img);
canvas.showImage(converter.convert(img));
Thread.sleep(INTERVAL);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Test gs = new Test();
Thread th = new Thread(gs);
th.start();
}
}
There is also post on configuration for JavaCV
You can modify the code and be able to save the images in regular interval and do rest of the processing you want.
Some time ago I've created generic Java library which can be used to take pictures with a PC webcam. The API is very simple, not overfeatured, can work standalone, but also supports additional webcam drivers like OpenIMAJ, JMF, FMJ, LTI-CIVIL, etc, and some IP cameras.
Link to the project is https://github.com/sarxos/webcam-capture
Example code (take picture and save in test.jpg):
Webcam webcam = Webcam.getDefault();
webcam.open();
BufferedImage image = webcam.getImage();
ImageIO.write(image, "JPG", new File("test.jpg"));
It is also available in Maven Central Repository or as a separate ZIP which includes all required dependencies and 3rd party JARs.
JMyron is very simple for use.
http://webcamxtra.sourceforge.net/
myron = new JMyron();
myron.start(imgw, imgh);
myron.update();
int[] img = myron.image();
Here is a similar question with some - yet unaccepted - answers. One of them mentions FMJ as a java alternative to JMF.
This kind of goes off of gt_ebuddy's answer using JavaCV, but my video output is at a much higher quality then his answer. I've also added some other random improvements (such as closing down the program when ESC and CTRL+C are pressed, and making sure to close down the resources the program uses properly).
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
public class HighRes extends JComponent implements Runnable {
private static final long serialVersionUID = 1L;
private static CanvasFrame frame = new CanvasFrame("Web Cam");
private static boolean running = false;
private static int frameWidth = 800;
private static int frameHeight = 600;
private static OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
private static BufferedImage bufImg;
public HighRes()
{
// setup key bindings
ActionMap actionMap = frame.getRootPane().getActionMap();
InputMap inputMap = frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
for (Keys direction : Keys.values())
{
actionMap.put(direction.getText(), new KeyBinding(direction.getText()));
inputMap.put(direction.getKeyStroke(), direction.getText());
}
frame.getRootPane().setActionMap(actionMap);
frame.getRootPane().setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, inputMap);
// setup window listener for close action
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
stop();
}
});
}
public static void main(String... args)
{
HighRes webcam = new HighRes();
webcam.start();
}
#Override
public void run()
{
try
{
grabber.setImageWidth(frameWidth);
grabber.setImageHeight(frameHeight);
grabber.start();
while (running)
{
final IplImage cvimg = grabber.grab();
if (cvimg != null)
{
// cvFlip(cvimg, cvimg, 1); // mirror
// show image on window
bufImg = cvimg.getBufferedImage();
frame.showImage(bufImg);
}
}
grabber.stop();
grabber.release();
frame.dispose();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void start()
{
new Thread(this).start();
running = true;
}
public void stop()
{
running = false;
}
private class KeyBinding extends AbstractAction {
private static final long serialVersionUID = 1L;
public KeyBinding(String text)
{
super(text);
putValue(ACTION_COMMAND_KEY, text);
}
#Override
public void actionPerformed(ActionEvent e)
{
String action = e.getActionCommand();
if (action.equals(Keys.ESCAPE.toString()) || action.equals(Keys.CTRLC.toString())) stop();
else System.out.println("Key Binding: " + action);
}
}
}
enum Keys
{
ESCAPE("Escape", KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0)),
CTRLC("Control-C", KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK)),
UP("Up", KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0)),
DOWN("Down", KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0)),
LEFT("Left", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0)),
RIGHT("Right", KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));
private String text;
private KeyStroke keyStroke;
Keys(String text, KeyStroke keyStroke)
{
this.text = text;
this.keyStroke = keyStroke;
}
public String getText()
{
return text;
}
public KeyStroke getKeyStroke()
{
return keyStroke;
}
#Override
public String toString()
{
return text;
}
}
You can try Java Webcam SDK library also.
SDK demo applet is available at link.
I have used JMF on a videoconference application and it worked well on two laptops: one with integrated webcam and another with an old USB webcam. It requires JMF being installed and configured before-hand, but once you're done you can access the hardware via Java code fairly easily.
You can try Marvin Framework. It provides an interface to work with cameras. Moreover, it also provides a set of real-time video processing features, like object tracking and filtering.
Take a look!
Real-time Video Processing Demo:
http://www.youtube.com/watch?v=D5mBt0kRYvk
You can use the source below. Just save a frame using MarvinImageIO.saveImage() every 5 second.
Webcam video demo:
public class SimpleVideoTest extends JFrame implements Runnable{
private MarvinVideoInterface videoAdapter;
private MarvinImage image;
private MarvinImagePanel videoPanel;
public SimpleVideoTest(){
super("Simple Video Test");
videoAdapter = new MarvinJavaCVAdapter();
videoAdapter.connect(0);
videoPanel = new MarvinImagePanel();
add(videoPanel);
new Thread(this).start();
setSize(800,600);
setVisible(true);
}
#Override
public void run() {
while(true){
// Request a video frame and set into the VideoPanel
image = videoAdapter.getFrame();
videoPanel.setImage(image);
}
}
public static void main(String[] args) {
SimpleVideoTest t = new SimpleVideoTest();
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
For those who just want to take a single picture:
WebcamPicture.java
public class WebcamPicture {
public static void main(String[] args) {
try{
MarvinVideoInterface videoAdapter = new MarvinJavaCVAdapter();
videoAdapter.connect(0);
MarvinImage image = videoAdapter.getFrame();
MarvinImageIO.saveImage(image, "./res/webcam_picture.jpg");
} catch(MarvinVideoInterfaceException e){
e.printStackTrace();
}
}
}
I used Webcam Capture API. You can download it from here
webcam = Webcam.getDefault();
webcam.open();
if (webcam.isOpen()) { //if web cam open
BufferedImage image = webcam.getImage();
JLabel imageLbl = new JLabel();
imageLbl.setSize(640, 480); //show captured image
imageLbl.setIcon(new ImageIcon(image));
int showConfirmDialog = JOptionPane.showConfirmDialog(null, imageLbl, "Image Viewer", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon(""));
if (showConfirmDialog == JOptionPane.YES_OPTION) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Save Image");
chooser.setFileFilter(new FileNameExtensionFilter("IMAGES ONLY", "png", "jpeg", "jpg")); //this file extentions are shown
int showSaveDialog = chooser.showSaveDialog(this);
if (showSaveDialog == 0) { //if pressed 'Save' button
String filePath = chooser.getCurrentDirectory().toString().replace("\\", "/");
String fileName = chooser.getSelectedFile().getName(); //get user entered file name to save
ImageIO.write(image, "PNG", new File(filePath + "/" + fileName + ".png"));
}
}
}
http://grack.com/downloads/school/enel619.10/report/java_media_framework.html
Using the Player with Swing
The Player can be easily used in a Swing application as well. The following code creates a Swing-based TV capture program with the video output displayed in the entire window:
import javax.media.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.event.*;
public class JMFTest extends JFrame {
Player _player;
JMFTest() {
addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e ) {
_player.stop();
_player.deallocate();
_player.close();
System.exit( 0 );
}
});
setExtent( 0, 0, 320, 260 );
JPanel panel = (JPanel)getContentPane();
panel.setLayout( new BorderLayout() );
String mediaFile = "vfw://1";
try {
MediaLocator mlr = new MediaLocator( mediaFile );
_player = Manager.createRealizedPlayer( mlr );
if (_player.getVisualComponent() != null)
panel.add("Center", _player.getVisualComponent());
if (_player.getControlPanelComponent() != null)
panel.add("South", _player.getControlPanelComponent());
}
catch (Exception e) {
System.err.println( "Got exception " + e );
}
}
public static void main(String[] args) {
JMFTest jmfTest = new JMFTest();
jmfTest.show();
}
}
Java usually doesn't like accessing hardware, so you will need a driver program of some sort, as goldenmean said. I've done this on my laptop by finding a command line program that snaps a picture. Then it's the same as goldenmean explained; you run the command line program from your java program in the takepicture() routine, and the rest of your code runs the same.
Except for the part about reading pixel values into an array, you might be better served by saving the file to BMP, which is nearly that format already, then using the standard java image libraries on it.
Using a command line program adds a dependency to your program and makes it less portable, but so was the webcam, right?
I believe the web-cam application software which comes along with the web-cam, or you native windows webcam software can be run in a batch script(windows/dos script) after turning the web cam on(i.e. if it needs an external power supply). In the bacth script , u can add appropriate delay to capture after certain time period. And keep executing the capture command in loop.
I guess this should be possible
-AD
There's a pretty nice interface for this in processing, which is kind of a pidgin java designed for graphics. It gets used in some image recognition work, such as that link.
Depending on what you need out of it, you might be able to load the video library that's used there in java, or if you're just playing around with it you might be able to get by using processing itself.
FMJ can do this, as can the supporting library it uses, LTI-CIVIL. Both are on sourceforge.
Recommand using FMJ for multimedia relatived java app.
Try using JMyron How To Use Webcam Using Java. I think using JMyron is the easiest way to access a webcam using java. I tried to use it with a 64-bit processor, but it gave me an error. It worked just fine on a 32-bit processor, though.