×
Namespaces

Variants
Actions
(Difference between revisions)

Saving a captured image in Java ME

From Nokia Developer Wiki
Jump to: navigation, search
Forum Nokia KB (Talk | contribs)
hamishwillee (Talk | contribs)
m (Hamishwillee - Add Abstract. Tidy wiki text)
(10 intermediate revisions by 3 users not shown)
Line 1: Line 1:
__NOTOC__
+
[[Category:Java ME]][[Category:Code Examples]][[Category:MMAPI (JSR-135)]][[Category:Code Snippet]][[Category:Symbian]][[Category:S60 3rd Edition (initial release)]][[Category:S60 3rd Edition FP1]][[Category:S60 3rd Edition FP2]][[Category:Nokia Belle]][[Category:Java Runtime 2.3 for Symbian]][[Category:Series 40 6th Edition FP1]][[Category:Series 40 Developer Platform 2.0]][[Category:Camera]]
__NOEDITSECTION__
+
{{Abstract|This code example demonstrates how to take a picture by camera and save it to file.}}
{{KBCS}}
+
 
{{CodeSnippet
+
{{ArticleMetaData <!-- v1.2 -->
|id=CS001261
+
|sourcecode= [[Media:SavingCapturedImage.zip]]
|platform=S60 3rd Edition, S60 3rd Edition, FP1, S60 3rd Edition, FP2
+
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
|devices=Nokia E70
+
|devices= Nokia E70, Nokia C3-01, Nokia Asha 306, Nokia E7-00
|category=Java ME
+
|sdk= [http://www.developer.nokia.com/Develop/Java/ Nokia SDK 1.1 for Java], [http://www.developer.nokia.com/Develop/Java/ Nokia SDK 2.0 for Java (beta)], [http://www.developer.nokia.com/info/sw.nokia.com/id/ec866fab-4b76-49f6-b5a5-af0631419e9c/S60_All_in_One_SDKs.html Nokia Symbian SDKs]<!-- SDK(s) built and tested against (e.g. [http://linktosdkdownload/ Nokia Qt SDK 1.1]) -->
|subcategory=Camera
+
|platform= Series 40, S60, Nokia Belle
|creationdate=January 7, 2009
+
|devicecompatability= <!-- Compatible devices (e.g.: All* (must have GPS) ) -->
|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
+
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
 +
|signing= <!-- Empty or one of Self-Signed, DevCert, Manufacturer -->
 +
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 +
|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
 +
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 +
|translated-by= <!-- [[User:XXXX]] -->
 +
|translated-from-title= <!-- Title only -->
 +
|translated-from-id= <!-- Id of translated revision -->
 +
|review-by= <!-- After re-review: [[User:username]] -->
 +
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 +
|update-by= <!-- After significant update: [[User:username]]-->
 +
|update-timestamp= <!-- After significant update: YYYYMMDD -->
 +
|creationdate= 20081127
 +
|author= [[User:Dekudin]]
 +
<!-- The following are not in current metadata -->
 +
|id= CS001261
 
}}
 
}}
  
 
==Overview==
 
==Overview==
 
This code snippet demonstrates how to take a picture by camera and save it to file.
 
  
 
Perform the following steps:
 
Perform the following steps:
# Check support of video capturing by calling the <tt>System.getProperty</tt> method with the <tt>supports.video.capture</tt> parameter.
+
# Check support of video capturing by calling the {{Icode|System.getProperty}} method with the {{Icode|supports.video.capture}} parameter.
# Call <tt>Manager.createPlayer</tt> method to create a camera player.
+
# Call {{Icode|Manager.createPlayer}} method to create a camera player.
 
# Initialize and start player.
 
# Initialize and start player.
# Get VideoControl object from the player and execute the <tt>VideoControl.getSnaphot</tt> method. This method returns array of bytes which represents captured image in specified format.
+
# Get VideoControl object from the player and execute the {{Icode|VideoControl.getSnaphot}} method. This method returns array of bytes which represents captured image in specified format.
 
# Open file and send array of bytes to it. After this, the file should be closed.
 
# Open file and send array of bytes to it. After this, the file should be closed.
 
# On exit from application, the camera player will be stopped and closed.
 
# On exit from application, the camera player will be stopped and closed.
 +
  
 
==Source file: CaptureAndSaveImage.java==
 
==Source file: CaptureAndSaveImage.java==
Line 126: Line 140:
 
     /**
 
     /**
 
     * 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() throws IOException, MediaException {
+
     private void createCamera() {
        player = Manager.createPlayer("capture://video");
+
try {
        player.realize();
+
    player = Manager.createPlayer("capture://image");
        player.prefetch();
+
}
 
+
catch (MediaException e) {
        videoControl = (VideoControl)player.getControl("VideoControl");
+
    try {
 +
        System.out.println("Couldn't set \"capture://video\"");
 +
    player = Manager.createPlayer("capture://video");
 +
    }
 +
    catch (MediaException ex) {
 +
   
 +
    }
 +
    catch (IOException ex) {
 +
   
 +
    }
 +
}
 +
catch (IOException e) {
 +
   
 +
}
 +
   
 +
try {
 +
    player.realize();
 +
    player.prefetch();
 +
}
 +
catch (MediaException e) {
 +
   
 +
}
 +
 +
videoControl = (VideoControl)player.getControl("VideoControl");
 
     }
 
     }
 
      
 
      
Line 301: Line 336:
  
 
</code>
 
</code>
 
  
 
==Postconditions==
 
==Postconditions==
Line 312: Line 346:
  
 
Executables and source files can be found in [[Media:SavingCapturedImage.zip]].
 
Executables and source files can be found in [[Media:SavingCapturedImage.zip]].
 
[[Category:Java ME]][[Category:Code Examples]][[Category:MMAPI (JSR-135)]]
 

Revision as of 09:10, 5 October 2012

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

Article Metadata
Code ExampleTested with
Devices(s): Nokia E70, Nokia C3-01, Nokia Asha 306, Nokia E7-00
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: dekudin (27 Nov 2008)
Last edited: hamishwillee (05 Oct 2012)

Contents

Overview

Perform the following steps:

  1. Check support of video capturing by calling the System.getProperty method with the supports.video.capture parameter.
  2. Call Manager.createPlayer method to create a camera player.
  3. Initialize and start player.
  4. Get VideoControl object from the player and execute the 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, the file should be closed.
  6. On exit from application, the 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", Command.OK, 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.
*/

private void createCamera() {
try {
player = Manager.createPlayer("capture://image");
}
catch (MediaException e) {
try {
System.out.println("Couldn't set \"capture://video\"");
player = Manager.createPlayer("capture://video");
}
catch (MediaException ex) {
 
}
catch (IOException ex) {
 
}
}
catch (IOException e) {
 
}
 
try {
player.realize();
player.prefetch();
}
catch (MediaException e) {
 
}
 
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() {
FileConnection file = null;
OutputStream outStream = null;
 
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
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
outStream = file.openOutputStream();
outStream.write(capturedImageData);
 
showAlert("Info", "Image is saved in " + fileName, cameraForm);
 
} catch(IOException ioExc) {
showAlert("IO error", ioExc.getMessage(), cameraForm);
} catch(MediaException mediaExc) {
showAlert("Media error", mediaExc.getMessage(), cameraForm);
} catch(Exception exc) {
showAlert("Error", exc.getMessage(), cameraForm);
} finally {
// Try to close file
try {
if(outStream != null) {
outStream.close();
}
if(file != null) {
file.close();
}
} catch(Exception exc) {
// Do nothing
}
}
}
 
/**
* 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, the user can take 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.

194 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×