Get Camera captured images and create bitmap image - blackberry

How to get camera captured images after native camera app exits ?
How to create an Bitmap image from the already existing SD card Jpeg image ?
I want to add this Bitmap to the screen.

ButtonField btn_Take_Pic = new ButtonField("Take a pic",Field.FIELD_HCENTER|FOCUSABLE)
{
protected boolean navigationClick(int status, int time) {
// TODO Auto-generated method stub
InvokeCameraScreen screen = new InvokeCameraScreen(CaptureImage.this);
screen.addCam();
UiApplication.getUiApplication().invokeLater (new Runnable() {
public void run()
{
//Perform screen changes here.
//Calling invalidate() on your screen forces the paint
//method to be called.
CaptureImage deal_Screen = new CaptureImage();
deal_Screen.invalidate();
}
});
return true;
}
};
Add body part of ImagePath() method
public void ImagePath(String path) {
try
{
Img_path = path;
EncodedImage.createEncodedImage(imgarr,0,imgarr.length);
Bitmap setimage = resizeBitmap(getBitmapFromFile(info.getImg_Path()),(int) (ScreenWidth *0.20),(int) (ScreenHeight *0.20));
Img_Field.setBitmap(setimage);
}
catch (Exception e) {
// TODO: handle exception
Dialog.alert("Ex path: " + e.toString());
}
}
implements ImagePath interface
public interface ImagePath {
public void ImagePath(String path);
}
public class InvokeCameraScreen implements FileSystemJournalListener {
private long lastUSN;
private String resultData, imagepath;
private VerticalFieldManager addToSCreen;
private boolean isAlreadeyExcuted = true;
private byte[] imageData;
private ImagePath pathImage;
public InvokeCameraScreen(ImagePath path) {
this.pathImage = path;
}
public void addCam() {
isAlreadeyExcuted = true;
getAddToSCreen().deleteAll();
startCam();
}
private void startCam() {
lastUSN = FileSystemJournal.getNextUSN();
UiApplication.getUiApplication().addFileSystemJournalListener(this);
try {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA,
new CameraArguments());
}
});
} catch (Exception e) {
System.out.println("CheckinFormScreen Exception: " + e.toString());
}
}
private void closeCamera() {
System.out.println("Closing Cam");
EventInjector.KeyEvent inject = new EventInjector.KeyEvent(
EventInjector.KeyEvent.KEY_DOWN, Characters.ESCAPE, 0, 25);
inject.post();
try {
Thread.sleep(500);
} catch (Exception e) {
}
UiApplication.getUiApplication().removeFileSystemJournalListener(this);
System.out.println("Done with closing cam");
}
public byte[] getImageData() {
return imageData;
}
public void setImageData(byte[] imageData) {
this.imageData = imageData;
}
public String getImagepath() {
return imagepath;
}
public void setImagepath(String imagepath) {
this.imagepath = imagepath;
}
public void fileJournalChanged() {
try {
closeCamera();
} catch (Exception e) {
}
long USN = FileSystemJournal.getNextUSN();
for (long i = USN - 1; i >= lastUSN && i < USN; --i) {
FileSystemJournalEntry entry = FileSystemJournal.getEntry(i);
if (entry == null) {
break;
}
if (entry.getEvent() == FileSystemJournalEntry.FILE_ADDED) {
String path = entry.getPath();
if (path != null && path.indexOf(".jpg") != -1) {
if (isAlreadeyExcuted) {
isAlreadeyExcuted = false;
resultData = "file://" + path;
pathImage.ImagePath(resultData);
// ShowUploadImage(resultData);
EventInjector.KeyEvent inject = new EventInjector.KeyEvent(
EventInjector.KeyEvent.KEY_DOWN,
Characters.ESCAPE, 0, 25);
inject.post();
inject.post();
if (Display.getWidth() == 480
&& Display.getHeight() == 360
|| Display.getWidth() == 360
&& Display.getHeight() == 480) {
try {
Thread.sleep(500);
inject.post();
} catch (Exception e) {
}
}
}
}
return;
}
}
}
public VerticalFieldManager getAddToSCreen() {
if (addToSCreen == null) {
addToSCreen = new VerticalFieldManager();
addToSCreen.setPadding(10, 10, 10, 10);
}
return addToSCreen;
}
public void setAddToSCreen(VerticalFieldManager addToSCreen) {
this.addToSCreen = addToSCreen;
}
private void ShowUploadImage(String path) {
}
}

try this,
CAll Below Class Like:
EncodedImage result = NcCamera.getInstance().getPictureTaken();
//
This is class in which you can get Camera images.
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class NcCamera extends MainScreen
{
private VideoControl videoControl;
private Field videoField;
public static EncodedImage pictureTaken = null;
private boolean initialized = false;
private boolean result;
public static boolean CAPTURING_DONE = true;
public static boolean CAPTURING_CANCELED = false;
private VerticalFieldManager main;
private static NcCamera instance;
CommonFunction cmn_fun;
public static byte[] raw;
public NcCamera()
{
super(NO_VERTICAL_SCROLL);
main = new VerticalFieldManager(USE_ALL_WIDTH | USE_ALL_HEIGHT)
{
// I wan't to force the backgound to black
public void paintBackground(Graphics g)
{
g.setBackgroundColor(0x000000);
g.clear();
}
};
super.add(main);
}
public void add(Field field)
{
main.add(field);
}
public EncodedImage getPictureTaken()
{
return pictureTaken;
}
public Screen getThisScreen()
{
return this;
}
public void reset()
{
pictureTaken = null;
result = CAPTURING_CANCELED;
}
public boolean showDialog()
{
result = CAPTURING_CANCELED;
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
UiApplication.getUiApplication().pushModalScreen(getThisScreen());
if (pictureTaken != null)
result = CAPTURING_DONE;
}
});
return result;
}
public static NcCamera getInstance()
{
if (instance == null)
instance = new NcCamera();
return instance;
}
public void onDisplay() {
if (!initialized)
{
initializeCamera();
if (videoField!=null) add(videoField);
else {
LabelField sorry = new LabelField("Sorry, we cannot use camera right now.") {
// I need to force the label to be white colored to be visible above
// it's underlying manager (that is black).
public void paint(Graphics g) {
int color = g.getColor();
g.setColor(0xffffff);
super.paint(g);
g.setColor(color);
}
};
add(sorry);
}
initialized = true;
}
}
private void initializeCamera()
{
try {
// Create a player for the Blackberry's camera
Player player = Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
// Set the player to the REALIZED state (see Player javadoc)
player.realize();
videoControl = (VideoControl) player.getControl("VideoControl");
if (videoControl != null)
{
videoField = (Field) videoControl.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE,
"net.rim.device.api.ui.Field");
videoControl.setDisplayFullScreen(true);
videoControl.setVisible(true);
}
player.start();
} catch (Exception e)
{
}
}
protected boolean invokeAction(int action)
{
boolean handled = super.invokeAction(action);
if (!handled)
{
switch (action)
{
case ACTION_INVOKE: // Trackball click
{
takePicture();
return true;
}
}
}
return handled;
}
public void takePicture()
{
try {
// Retrieve the raw image from the VideoControl and
// create a screen to display the image to the user.
raw = videoControl.getSnapshot(null);
// SaveImageSdcard(raw);
Bitmap img= Bitmap.createBitmapFromBytes(raw, 0, raw.length,3);
Constants.PICTURE_TAKEN=cmn_fun.resizeBitmap(img, 150, 150);
// save the picture taken into pictureTaken variable
pictureTaken = EncodedImage.createEncodedImage(raw, 0, raw.length);
result = CAPTURING_DONE;
close();
} catch (Exception e)
{
}
}
}
public boolean keyDown(int keycode,
int time) {
if (keycode == 1769472)
{ // escape pressed
reset();
close();
return true;
}
return super.keyDown(keycode, time);
}
}

Related

Eclipse Java KeyEvent.VK_LEFT (NOT WORKING)

This is some code that should create a oval that can be controlled via arrow keys.
I have done lots of research but I haven't been able to find a solution to my problem.
I am using Eclipse Mars with the Java language. Here is my code.
package com.game;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Game extends Applet implements KeyListener, Runnable {
public int x,y;
public boolean up,down,left,right;
public Image offscreen;
public Graphics d;
public void init(){
setSize(854,480);
Thread th = new Thread(this);
th.start();
offscreen = createImage(854,480);
d = offscreen.getGraphics();
this.addKeyListener(new Game());
}
public void run(){
while(true)
{
System.out.println("X: " + x);
System.out.println("Y: " + y);
if(left == true){
x--;
}
if(right == true){
x++;
}
if(up == true){
y--;
}
if(down == true){
y++;
}
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void keyTyped(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
left = true;
System.out.println("Left key pressed");
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
right = true;
System.out.println("Right key pressed");
}
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
left = true;
System.out.println("Left key pressed");
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
right = true;
System.out.println("Left key pressed");
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
left = false;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
right = false;
}
}
public void paint (Graphics g){
d.clearRect(0, 0, 854, 480);
d.drawOval(x, y, 20, 20);
g.drawImage(offscreen, 0, 0, this);
}
public void update(Graphics g){
paint(g);
}
}
When running this code, pressing arrow keys is not doing anything.

How to determine the state of the GPS in BlackBerry?

i want to know how determine the state of the GPS, soo if the state is different to AVAILABLE i don't create the Listener to save battery.
But in execution always enter for the else create the LocationListener and not for the if.
Here is my code
public class UpdateGPS extends Thread{
public void run(){
while (true){
try{
getGPS();
sleep(30000); //Update GPS for each 30secs
}
catch(Exception e){}
}
}
}
public void getGPS() {
String state = "RUNNING";
BlackBerryCriteria myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_ASSIST);
try {
locationProvider = LocationProvider.getInstance(myCriteria);
if (locationProvider != null) {
if (locationProvider.getState() != locationProvider.AVAILABLE) {
state= "STOP";
}
else {
locationProvider.setLocationListener(
new LocationListenerImplementacion(),valor_reintento, -1, -1);
}
}
}
catch(Exception e) {}
}
private class LocationListenerImplementacion implements LocationListener {
public void locationUpdated(LocationProvider provider,Location location) {
if (location.isValid()) {
//GET DATA
}
else {}
public void providerStateChanged(LocationProvider provider, int newState){
}
}

How to save captured image in a folder in blackberry?

I am developing application which has camera functionality. i want to save that captured image in my project folder.Can any one help me please.
thanx in advance.
This below code may help you:
Add this to Main Screen which you want to show the camera:
captureImage=new MenuItem("Capture Images",10,100)
{
public void run()
{
synchronized (Application.getEventLock())
{
captureImage();
}
}
};
addMenuItem(captureImage);
The code for captureImage() method is:
private void captureImage()
{
try
{
player = javax.microedition.media.Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
player.realize();
_videoControl = (VideoControl) player.getControl("VideoControl");
if (_videoControl != null)
{
Field videoField = (Field) _videoControl.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
_videoControl.setDisplayFullScreen(true);
_videoControl.setVisible(true);
player.start();
if(videoField != null)
{
add(videoField);
}
}
}
catch(Exception e)
{
if(player!=null)
{
player.close();
}
Dialog.alert(e.toString());
}
}
The below code is save the image into the sdcard or device card. Override the invokeAction(int action) Method
protected boolean invokeAction(int action)
{
boolean handled = super.invokeAction(action);
if(SdcardTest.SdcardAvailabulity())//I am checking here that the sdcard is there of or not.....?
{
//PATH = "file:///SDCard/BlackBerry/pictures/"+"Image_"+System.currentTimeMillis()+".jpg";
PATH = System.getProperty("fileconn.dir.memorycard.photos")+"Image_"+System.currentTimeMillis()+".jpg";//here "str" having the current Date and Time;
}
else
{
PATH = System.getProperty("fileconn.dir.photos")+"Image_"+System.currentTimeMillis()+".jpg";
}
if(!handled)
{
if(action == ACTION_INVOKE)
{
try
{
byte[] rawImage = _videoControl.getSnapshot(null);
fileconn=(FileConnection)Connector.open(PATH);
if(fileconn.exists())
{
fileconn.delete();
}
fileconn.create();
OutputStream os=fileconn.openOutputStream();
os.write(rawImage);
fileconn.close();
os.close();
Status.show("Image is Captured",200);
if(player!=null)
player.close();
}
catch(Exception e)
{
if(player!=null)
{
player.close();
}
if(fileconn!=null)
{
try
{
fileconn.close();
}
catch (IOException e1)
{
//if the action is other than click the trackwheel(means go to the menu options) then we do nothing;
}
}
}
}
}
return handled;
}
try this for image snap
Note: you can not store in resource folder you can only store in SDcard
class screen extends MainScreen implements FieldChangeListener
{
private VideoControl vc;
private String encoding;
private Player p;
private Field viewFinder;
private BitmapField bitmapField;
private ButtonField btn;
public screen() {
btn=new ButtonField("snap",Field.FOCUSABLE);
btn.setChangeListener(this);
add(btn);
}
public void fieldChanged(Field field, int context) {
if(field==btn)
{
try{
p = Manager.createPlayer("capture://video");
p.realize();
p.prefetch();
p.start();
vc = (VideoControl) p.getControl("VideoControl");
viewFinder = (Field)vc.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
vc.setVisible(true);
final String imageType = "encoding=jpeg&width=640&height=480&quality=superfine";
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
byte[] image = vc.getSnapshot(imageType);
FileConnection conn = (FileConnection)Connector.open("file:///store/home/user/pictures/"+System.currentTimeMillis()+".jpeg", Connector.READ_WRITE);
conn.create();
OutputStream out = conn.openOutputStream();
out.write(image);
out.flush();
out.close();
conn.close();
Bitmap image1 = Bitmap.createBitmapFromBytes(imageBytes, 0, imageBytes.length, 4);
bitmapField.setBitmap(image1);
add(bitmapField);
}
});
} catch (Exception me){
}
}
}
}
for more operations please use this
http://supportforums.blackberry.com/rim/attachments/rim/java_dev#tkb/226/1/SnapshotSample.zip
if you want to save an image from camera to your device you can use the following code.
try
{
focusControl.startAutoFocus();
byte[] image = videoControl.getSnapshot(null);
String message = "Captured "+image.length+" bytes of JPG data";
debug(message);
FileConnection conn = (FileConnection)Connector.open("file:///store/home/user/pictures/"+(new Date()).getTime()+".jpg", Connector.READ_WRITE);
conn.create();
OutputStream out = conn.openOutputStream();
out.write(image);
out.flush();
out.close();
conn.close();
Dialog.alert(message);
}
catch (Exception e) {
Dialog.alert("Capture failed due to: "+e.getMessage());
}
If you want to save the images in your Project/res or Project/src during runtime, you cant do that.
You can save image in SDcard/device.
Why would you want to save it in your project source?

Launch the video recorder from BlackBerry app

Are there any APIs to launch the video recording app? I want to invoke the video recorder through my app, record a video, then save that video to the server.
ApplicationManager.getApplicationManager().launch("net_rim_bb_videorecorder");
This will help you open the application. If you want to start recording, you may need to simulate a key input.
btw: CameraArguments(ARG_VIDEO_RECORDER) is introduced since jde4.7, so it's not compatible with the previous OS's. So the previous method is better.
Finally find the solution from BB docs .
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.system.*;
import java.lang.*;
import javax.microedition.media.*;
import java.io.*;
import javax.microedition.media.control.*;
public class VideoRecordingDemo extends UiApplication
{
public static void main(String[] args)
{
VideoRecordingDemo app = new VideoRecordingDemo();
app.enterEventDispatcher();
}
public VideoRecordingDemo()
{
pushScreen(new VideoRecordingDemoScreen());
}
private class VideoRecordingDemoScreen extends MainScreen
{
private VideoRecorderThread _recorderThread;
public VideoRecordingDemoScreen()
{
setTitle("Video recording demo");
addMenuItem(new StartRecording());
addMenuItem(new StopRecording());
}
private class StartRecording extends MenuItem
{
public StartRecording()
{
super("Start recording", 0, 100);
}
public void run()
{
try
{
VideoRecorderThread newRecorderThread = new VideoRecorderThread();
newRecorderThread.start();
_recorderThread = newRecorderThread;
}
catch (Exception e)
{
Dialog.alert(e.toString());
}
}
}
private class StopRecording extends MenuItem
{
public StopRecording()
{
super("Stop recording", 0, 100);
}
public void run()
{
try
{
if (_recorderThread != null)
{
_recorderThread.stop();
}
}
catch (Exception e)
{
Dialog.alert(e.toString());
}
}
}
private class VideoRecorderThread extends Thread implements javax.microedition.media.PlayerListener
{
private Player _player;
private RecordControl _recordControl;
VideoRecorderThread()
{
}
public void run()
{
try
{
_player = javax.microedition.media.Manager.createPlayer("capture://video?encoding=video/3gpp");
_player.addPlayerListener(this);
_player.realize();
VideoControl videoControl = (VideoControl) _player.getControl("VideoControl");
_recordControl = (RecordControl) _player.getControl( "RecordControl" );
Field videoField = (Field) videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
try
{
videoControl.setDisplaySize( Display.getWidth(), Display.getHeight() );
}
catch( MediaException me )
{
// setDisplaySize is not supported
}
add(videoField);
_recordControl.setRecordLocation("file:///store/home/user/VideoRecordingTest.3gpp" );
_recordControl.startRecord();
_player.start();
}
catch( IOException e )
{
Dialog.alert(e.toString());
}
catch( MediaException e )
{
Dialog.alert(e.toString());
}
}
public void stop()
{
if (_player != null)
{
_player.close();
_player = null;
}
if (_recordControl != null)
{
_recordControl.stopRecord();
try
{
_recordControl.commit();
}
catch (Exception e)
{
Dialog.alert(e.toString());
}
_recordControl = null;
}
}
public void playerUpdate(Player player, String event, Object eventData)
{
Dialog.alert("Player " + player.hashCode() + " got event " + event + ": " + eventData);
}
}
}
}

Adding Editfield to Popup screen

I have created my own custom popup screen to which now I am trying to add a editfield , everything seems to be fine but the problem is that I am not able to write anything in the edit field
class sveetIt extends PopupScreen implements FieldChangeListener, DialogClosedListener {
Hashtable pitemData;
ButtonField sveetNowlabelField;
ButtonField sveetLaterlabelField;
WatingScreen watingScreen;
long scheduledTime;
Dialog updateDialog;
public sveetIt() {
super(new MyCustimGridFieldManager());
LabelField messageLabelField = new LabelField("Enter your Sveet Message:",Field.FIELD_HCENTER) {
protected void paint(Graphics graphics) {
graphics.setColor(Color.YELLOWGREEN);
super.paint(graphics);
}
};
EditField sveetTexteditField= new EditField(null, "Sveet Message", 50, EditField.FIELD_HCENTER
| EditField.FIELD_VCENTER
| EditField.NON_SPELLCHECKABLE | EditField.NO_NEWLINE);
VerticalFieldManager buttonVFManager = new VerticalFieldManager(VerticalFieldManager.FIELD_HCENTER);
HorizontalFieldManager hfManager = new HorizontalFieldManager();
sveetNowlabelField = new ButtonField("Sveet Now");
sveetLaterlabelField = new ButtonField("Sveet Later");
sveetNowlabelField.setChangeListener(this);
sveetLaterlabelField.setChangeListener(this);
add(messageLabelField);
add(sveetTexteditField);
hfManager.add(sveetNowlabelField);
hfManager.add(sveetLaterlabelField);
buttonVFManager.add(hfManager);
add(buttonVFManager);
}
public boolean isEditable() {
return true;
}
protected boolean keyChar(char c, int status, int time) {
boolean retVal = false;
if (c == Characters.ESCAPE) {
Ui.getUiEngine().popScreen(this);
retVal = super.keyChar(c, status, time);
}
return retVal;
}
public void fieldChanged(Field field, int context) {
if (sveetNowlabelField == field) {
//Here directly starts uploading file
beginUpload();
} else if (sveetLaterlabelField == field) {
// first picks up time when to upload
scheduledTime = getScheduleTime();
if(scheduledTime!=1L) {
//now begins uploading file
beginUpload();
}
}}
class SubscribingThread extends StoppableThread {
int network = 50;
public void run() {
}
}
public void beginUpload() {
try {
watingScreen = new WatingScreen("Uploading Sveet...");
/*
* UiApplication.getUiApplication().invokeAndWait( new Runnable() {
* public void run() { Ui.getUiEngine().pushScreen(watingScreen); }
* });
*/
BaseScreen.pushScreen(watingScreen);
Thread thread = new Thread(new Runnable() {
public void run() {
uploadToServer();
}
});
thread.start();
// uploadToServer();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
private long getScheduleTime() {
scheduledTime = 0;
final DateTimePicker datePick = DateTimePicker.createInstance();
UiApplication.getUiApplication().invokeAndWait(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Calendar currentCalendar = datePick.getDateTime();
datePick.setMinimumDate(currentCalendar);
datePick.doModal();
Calendar cal = datePick.getDateTime();
if (cal.after(currentCalendar)) {
Date date = cal.getTime();
Dialog.alert("You selected " + date.toString());
scheduledTime = date.getTime();
} else {
Dialog.alert("Invalid date selection");
scheduledTime = 1L;
}
}
});
System.out.println("date in MilliSeconds is:" + scheduledTime);
return scheduledTime;
}
public void uploadToServer() {
} public void dialogClosed(Dialog arg0, int arg1) {
}
}
class MyCustimGridFieldManager extends VerticalFieldManager {
public MyCustimGridFieldManager() {
super(VERTICAL_SCROLL | USE_ALL_WIDTH | FIELD_HCENTER);
}
protected void paint(Graphics gr) {
super.paint(gr);
}
}
try this:
protected boolean keyChar(char c, int status, int time) {
if (c == Characters.ESCAPE) {
Ui.getUiEngine().popScreen(this);
}
return super.keyChar(c, status, time);
}
Try adding Field.EDITABLE to your style for the EditField.

Resources