J2ME program to capture a picture through mobile phone
Here is a simple J2ME program to take a snapshot using the camera of the mobile phone.This program display the camera and allow the user to capture the image and store the picture in the specific location. Import the respective packages after copying the following code.
public class CameraMIDlet extends MIDlet
implements CommandListener, Runnable {
private Display mDisplay;
private Form mMainScreen;
private Item mVideoItem;
private VideoControl mVidc;
private Command mCaptureCommand;
private Player mPlayer = null;
private boolean mEndNow = false;
private FileConnection fileCon = null;
public void startApp()
{
mDisplay = Display.getDisplay(this);
if (mMainScreen == null) {
// System.out.println("File Version:"+System.getProperty("microedition.io.file.FileConnection.version"));
mMainScreen = new Form("My Camera");
mMainScreen.addCommand(new Command("Exit", Command.EXIT, 0));
mCaptureCommand = new Command("Capture", Command.SCREEN, 0);
mMainScreen.addCommand(mCaptureCommand);
mMainScreen.setCommandListener(this);
}
mDisplay.setCurrent(mMainScreen);
Thread t = new Thread(this);
t.start();
mEndNow = false;
}
public void pauseApp() {}
public void destroyApp(boolean unconditional)
{
if (mPlayer != null)
{
mPlayer.close();
}
mEndNow = true;
synchronized(this)
{
this.notify();
}
}
public void commandAction(Command c, Displayable s) {
if (c.getCommandType() == Command.EXIT) {
destroyApp(true);
notifyDestroyed();
}
else {
// Capture
synchronized(this) {
this.notify();
}
}
}
public void run()
{
viewCamera();
while(!mEndNow)
{
synchronized(this)
{
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
if (!mEndNow)
try
{
byte[] rawImg = mVidc.getSnapshot(null);
int counter = 0;
while(true)
{
counter ++;
String filename = "file:///C:/Pictures/Snap"+counter+".png";
fileCon = (FileConnection) Connector.open(filename);
if(fileCon.exists())
{
continue;
}
else
{
fileCon.create();
break;
}
}
OutputStream out = fileCon.openOutputStream();
out.write(rawImg);
out.close();
fileCon.close();
} catch (MediaException ex) {
continue;
}
catch (Exception e)
{
showException(e);
}
}
}
}
private void viewCamera() {
try
{
mPlayer = Manager.createPlayer("capture://video");
mPlayer.realize();
if ((mVidc = (VideoControl)
mPlayer.getControl("VideoControl")) != null)
{
mVideoItem = (Item)
mVidc.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null);
mMainScreen.append(mVideoItem);
}
mPlayer.start();
mDisplay.setCurrent(mMainScreen);
}
catch (Exception e) {
showException(e);
return;
}
}
private void showException(Exception e) {
Alert a = new Alert("Exception", e.toString(), null, null);
a.setTimeout(Alert.FOREVER);
mDisplay.setCurrent(a, mMainScreen);
}
}
0 comments:
Post a Comment