×
Namespaces

Variants
Actions
(Difference between revisions)

Saving a captured image in Java ME

From Nokia Developer Wiki
Jump to: navigation, search
dekudin (Talk | contribs)
(New page: __NOTOC__ __NOEDITSECTION__ {{CodeSnippet |id=  |platform=S60 3rd Edition, FP2 |devices=Nokia E70 |category=Java ME |subcategory=Camera |creationdate=October 20, 2008 |keywords=javax....)
 
dekudin (Talk | contribs)
Line 27: Line 27:
  
 
<code java>
 
<code java>
 +
  
 
import javax.microedition.midlet.MIDlet;
 
import javax.microedition.midlet.MIDlet;
Line 35: Line 36:
 
import javax.microedition.lcdui.Command;
 
import javax.microedition.lcdui.Command;
 
import javax.microedition.lcdui.Item;
 
import javax.microedition.lcdui.Item;
 +
import javax.microedition.lcdui.Alert;
  
 
import javax.microedition.media.Manager;
 
import javax.microedition.media.Manager;
Line 43: Line 45:
 
import javax.microedition.io.Connector;
 
import javax.microedition.io.Connector;
 
import javax.microedition.io.file.FileConnection;
 
import javax.microedition.io.file.FileConnection;
 +
 
import java.io.OutputStream;
 
import java.io.OutputStream;
 +
import java.io.IOException;
  
 
public class CaptureAndSaveImage extends MIDlet implements CommandListener {
 
public class CaptureAndSaveImage extends MIDlet implements CommandListener {
Line 62: Line 66:
 
     // Video control of camera
 
     // Video control of camera
 
     private VideoControl videoControl;
 
     private VideoControl videoControl;
 +
 +
    // Alert to be displayed if error occurs.
 +
    private Alert alert;
 
      
 
      
 
     /**
 
     /**
Line 77: Line 84:
  
 
         if(checkCameraSupport() == false) {
 
         if(checkCameraSupport() == false) {
             exitMIDlet();
+
             //showAlert("Alert", "Camera is not supported!", null);
 +
            //return;
 
         }
 
         }
 
          
 
          
         createCameraForm();
+
         try {
        createCamera();
+
            createCameraForm();
        addCameraToForm();
+
            createCamera();  
 +
            addCameraToForm();
 +
            startCamera();
 +
        } catch(IOException ioExc) {
 +
            showAlert("IO error", ioExc.getMessage(), null);
 +
        } catch(MediaException mediaExc) {
 +
            showAlert("Media error", mediaExc.getMessage(), null);
 +
        }
 
     }
 
     }
 
          
 
          
Line 107: Line 122:
 
     private boolean checkCameraSupport() {
 
     private boolean checkCameraSupport() {
 
         String propValue = System.getProperty("supports.video.capture");
 
         String propValue = System.getProperty("supports.video.capture");
         if(propValue == null) {
+
         return (propValue != null) && propValue.equals("true");
            return false;
+
        }
+
        if(propValue.equals("true") == true) {
+
            return true;
+
        }
+
        return false;
+
 
     }     
 
     }     
 
      
 
      
 
     /**
 
     /**
     * Creates camera control and places it to cameraForm.
+
     * Creates camera control and places it to cameraForm.
 +
    * @throws IOException if creation of player is failed.
 +
    * @throws MediaException if creation of player is failed.
 
     */
 
     */
     private void createCamera() {
+
     private void createCamera() throws IOException, MediaException {
         try {
+
         player = Manager.createPlayer("capture://video");
            player = Manager.createPlayer("capture://video");
+
        player.realize();
            player.realize();
+
        player.prefetch();
            player.prefetch();
+
  
            videoControl = (VideoControl)player.getControl("VideoControl");
+
        videoControl = (VideoControl)player.getControl("VideoControl");
        } catch(Exception e) {
+
            // TODO: handle exception.
+
            exitMIDlet();
+
        }       
+
 
     }
 
     }
 
      
 
      
Line 142: Line 148:
 
     /**
 
     /**
 
     * Start camera player
 
     * Start camera player
 +
    * @throws IOException if starting of player is failed.
 +
    * @throws MediaException if starting of player is failed.
 
     */
 
     */
     private void startCamera() {
+
     private void startCamera() throws IOException, MediaException  {
         try {
+
         if(player.getState() == Player.PREFETCHED) {
            if(player.getState() == Player.PREFETCHED) {
+
            player.start();
                player.start();
+
            }
+
        } catch(Exception e) {
+
            // TODO: handle exception.
+
            exitMIDlet();
+
 
         }
 
         }
 
     }
 
     }
Line 159: Line 162:
 
     private void captureAndSaveImage() {
 
     private void captureAndSaveImage() {
 
         try {
 
         try {
 +
            if(checkPngEncodingSupport() == false) {
 +
                throw new Exception("Png encoding is not supported!");
 +
            }
 +
           
 
             // Capture image
 
             // Capture image
 
             byte[] capturedImageData =  
 
             byte[] capturedImageData =  
                     videoControl.getSnapshot("encoding=jpeg");
+
                     videoControl.getSnapshot("encoding=png");
 
              
 
              
 
             // Get path to photos folder.
 
             // Get path to photos folder.
 
             String dirPhotos = System.getProperty("fileconn.dir.photos");
 
             String dirPhotos = System.getProperty("fileconn.dir.photos");
 
             if(dirPhotos == null) {
 
             if(dirPhotos == null) {
                 throw new NullPointerException("Unable get photos folder name");
+
                 throw new Exception("Unable get photos folder name");
 
             }
 
             }
 
              
 
              
             String fileName = dirPhotos + "CapturedImage.jpg";
+
             String fileName = dirPhotos + "CapturedImage.png";
 
             // Open file
 
             // Open file
 
             FileConnection file = (FileConnection)Connector.open(fileName,  
 
             FileConnection file = (FileConnection)Connector.open(fileName,  
Line 183: Line 190:
 
             outStream.close();
 
             outStream.close();
 
             file.close();
 
             file.close();
         } catch(Exception e) {
+
           
             // TODO: handle exception.
+
            showAlert("Info", "Image is saved in " + fileName, cameraForm);
 +
         }
 +
        catch(Exception e) {
 +
             showAlert("Error", e.getMessage(), cameraForm);
 
         }
 
         }
 
     }     
 
     }     
 +
 +
    /**
 +
    * Checks png encoding support
 +
    * @return true if png encoding is supported false otherwise.
 +
    */
 +
    private boolean checkPngEncodingSupport() {
 +
        String encodings = System.getProperty("video.snapshot.encodings");
 +
        return (encodings != null) && (encodings.indexOf("png") != -1);
 +
    }
 
          
 
          
 
     /**
 
     /**
Line 193: Line 212:
 
     */
 
     */
 
     public void startApp() {
 
     public void startApp() {
         display.setCurrent(cameraForm);
+
         if ( videoControl != null ) {
         startCamera();
+
            display.setCurrent(cameraForm);
 +
         }
 
     }     
 
     }     
 
      
 
      
Line 211: Line 231:
 
         notifyDestroyed();
 
         notifyDestroyed();
 
     }
 
     }
 +
   
 +
    /**
 +
    * Shows alert with specified title and text. If next displayable is not
 +
    * specified then application will be closed after alert closing.
 +
    * @param title - Title of alert.
 +
    * @param message - text of alert.
 +
    * @param nextDisp - next displayable. Can be null.
 +
    */
 +
    private void showAlert(String title, String message, Displayable nextDisp) {
 +
        alert = new Alert(title);
 +
        alert.setString(message);
 +
        alert.setTimeout(Alert.FOREVER);
 +
 +
        if(nextDisp != null) {
 +
            display.setCurrent(alert, nextDisp);
 +
        } else {
 +
            display.setCurrent(alert);
 +
            alert.setCommandListener(this);
 +
        }
 +
    }       
 
      
 
      
 
     /**
 
     /**
Line 218: Line 258:
 
     public void destroyApp(boolean unconditional) {
 
     public void destroyApp(boolean unconditional) {
 
         if(player != null) {
 
         if(player != null) {
             try {
+
             player.deallocate();
                player.stop();
+
            player.close();
                player.deallocate();
+
                player.close();
+
            } catch (MediaException ex) {
+
                // TODO: handle exception
+
            }
+
 
         }
 
         }
 
     }
 
     }
Line 241: Line 276:
 
         // Handles "exit" command from forms
 
         // Handles "exit" command from forms
 
         if(command == cmdExit) {
 
         if(command == cmdExit) {
 +
            exitMIDlet();
 +
        }
 +
        // Handle "ok" command from alert
 +
        if(displayable == alert) {
 
             exitMIDlet();
 
             exitMIDlet();
 
         }
 
         }
Line 253: Line 292:
 
Camera viewfinder is shown on display.  
 
Camera viewfinder is shown on display.  
  
By choosing "Capture image" menu command user can make a snapshot and save it to CapturedImage.jpg file in photos folder. Image will be saved to file with jpeg encoding.
+
By choosing "Capture image" menu command user can make a snapshot and save it to CapturedImage.png file in photos folder. Image will be saved to file with png encoding.
  
 
==Supplementary material==
 
==Supplementary material==

Revision as of 14:46, 8 December 2008


Article Metadata
Tested with
Devices(s): Nokia E70
CompatibilityArticle
Keywords: javax.microedition.media.Manager, javax.microedition.media.Player, javax.microedition.media.control.VideoControl, javax.microedition.media.Manager.createPlayer, javax.microedition.media.Player.getControl, javax.microedition.media.control.VideoControl.getSnapshot
Created: (20 Oct 2008)
Last edited: dekudin (08 Dec 2008)

Overview

This code snippet demonstrates how to take a picture by camera and save it to file.

To take a picture by camera and save it to file following steps should be performed:

  1. Check support of video capturing by calling System.getProperty method with supports.video.capture parameter.
  2. Call Manager.createPlayer method to create camera player.
  3. Initialize and start player.
  4. Get VideoControl object from player and execute VideoControl.getSnaphot method. This method returns array of bytes which represents captured image in specified format.
  5. Open file and send array of bytes to it. After this file should be closed.
  6. On exit from application camera player will be stopped and closed.


Source file: CaptureAndSaveImage.java

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.Alert;
 
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;
import javax.microedition.media.MediaException;
 
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
 
import java.io.OutputStream;
import java.io.IOException;
 
public class CaptureAndSaveImage extends MIDlet implements CommandListener {
 
private Display display;
 
// Form where camera viewfinder is placed
private Form cameraForm;
 
// Command for capturing image by camera and saving it.
// Placed in cameraForm.
private Command cmdCapture;
// Command for exiting from midlet. Placed in cameraForm.
private Command cmdExit;
 
// Player for camera
private Player player;
// Video control of camera
private VideoControl videoControl;
 
// Alert to be displayed if error occurs.
private Alert alert;
 
/**
* Constructor.
*/

public CaptureAndSaveImage() {
InitializeComponents();
}
 
/**
* Initializes components of midlet.
*/

private void InitializeComponents() {
display = Display.getDisplay(this);
 
if(checkCameraSupport() == false) {
//showAlert("Alert", "Camera is not supported!", null);
//return;
}
 
try {
createCameraForm();
createCamera();
addCameraToForm();
startCamera();
} catch(IOException ioExc) {
showAlert("IO error", ioExc.getMessage(), null);
} catch(MediaException mediaExc) {
showAlert("Media error", mediaExc.getMessage(), null);
}
}
 
/**
* Creates and returns form where the camera control will be placed.
*/

private void createCameraForm() {
// Create camera form
cameraForm = new Form("Camera");
// Create commands for this form
cmdCapture = new Command("Capture image", Command.SCREEN, 0);
cmdExit = new Command("Exit", Command.EXIT, 0);
// Add commands to form
cameraForm.addCommand(cmdCapture);
cameraForm.addCommand(cmdExit);
// Set midlet as command listener for this form
cameraForm.setCommandListener(this);
}
 
/**
* Check camera support.
* @return true if camera is supported, false otherwise.
*/

private boolean checkCameraSupport() {
String propValue = System.getProperty("supports.video.capture");
return (propValue != null) && propValue.equals("true");
}
 
/**
* Creates camera control and places it to cameraForm.
* @throws IOException if creation of player is failed.
* @throws MediaException if creation of player is failed.
*/

private void createCamera() throws IOException, MediaException {
player = Manager.createPlayer("capture://video");
player.realize();
player.prefetch();
 
videoControl = (VideoControl)player.getControl("VideoControl");
}
 
/**
* Adds created camera as item to cameraForm.
*/

private void addCameraToForm() {
cameraForm.append((Item)videoControl.
initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null));
}
 
/**
* Start camera player
* @throws IOException if starting of player is failed.
* @throws MediaException if starting of player is failed.
*/

private void startCamera() throws IOException, MediaException {
if(player.getState() == Player.PREFETCHED) {
player.start();
}
}
 
/**
* Saves image captured by camera.
*/

private void captureAndSaveImage() {
try {
if(checkPngEncodingSupport() == false) {
throw new Exception("Png encoding is not supported!");
}
 
// Capture image
byte[] capturedImageData =
videoControl.getSnapshot("encoding=png");
 
// Get path to photos folder.
String dirPhotos = System.getProperty("fileconn.dir.photos");
if(dirPhotos == null) {
throw new Exception("Unable get photos folder name");
}
 
String fileName = dirPhotos + "CapturedImage.png";
// Open file
FileConnection file = (FileConnection)Connector.open(fileName,
Connector.READ_WRITE);
// If there is no file then create it
if(file.exists() == false) {
file.create();
}
// Write data received from camera while making snapshot to file
OutputStream outStream = file.openOutputStream();
outStream.write(capturedImageData);
// Close file
outStream.close();
file.close();
 
showAlert("Info", "Image is saved in " + fileName, cameraForm);
}
catch(Exception e) {
showAlert("Error", e.getMessage(), cameraForm);
}
}
 
/**
* Checks png encoding support
* @return true if png encoding is supported false otherwise.
*/

private boolean checkPngEncodingSupport() {
String encodings = System.getProperty("video.snapshot.encodings");
return (encodings != null) && (encodings.indexOf("png") != -1);
}
 
/**
* From MIDlet.
* Signals the MIDlet that it has entered the Active state.
*/

public void startApp() {
if ( videoControl != null ) {
display.setCurrent(cameraForm);
}
}
 
/**
* From MIDlet.
* Signals the MIDlet to enter the Paused state.
*/

public void pauseApp() {
// TODO: pause player if it is running.
}
 
/**
* Performs exit from midlet.
*/

public void exitMIDlet() {
notifyDestroyed();
}
 
/**
* Shows alert with specified title and text. If next displayable is not
* specified then application will be closed after alert closing.
* @param title - Title of alert.
* @param message - text of alert.
* @param nextDisp - next displayable. Can be null.
*/

private void showAlert(String title, String message, Displayable nextDisp) {
alert = new Alert(title);
alert.setString(message);
alert.setTimeout(Alert.FOREVER);
 
if(nextDisp != null) {
display.setCurrent(alert, nextDisp);
} else {
display.setCurrent(alert);
alert.setCommandListener(this);
}
}
 
/**
* From MIDlet.
* Signals the MIDlet to terminate and enter the Destroyed state.
*/

public void destroyApp(boolean unconditional) {
if(player != null) {
player.deallocate();
player.close();
}
}
 
/**
* From CommandListener.
* Indicates that a command event has occurred on Displayable displayable.
* @param command - a Command object identifying the command.
* @param displayable - the Displayable on which this event has occurred.
*/

public void commandAction(Command command, Displayable displayable) {
// Handles "Capture image" command from cameraForm
if(command == cmdCapture) {
captureAndSaveImage();
}
// Handles "exit" command from forms
if(command == cmdExit) {
exitMIDlet();
}
// Handle "ok" command from alert
if(displayable == alert) {
exitMIDlet();
}
}
}


Postconditions

Camera viewfinder is shown on display.

By choosing "Capture image" menu command user can make a snapshot and save it to CapturedImage.png file in photos folder. Image will be saved to file with png encoding.

Supplementary material

Executables and source files can be found in Media:SavingCapturedImage.zip

178 page views in the last 30 days.
×