Escolar Documentos
Profissional Documentos
Cultura Documentos
EXAMPLE
L. Grewe
See http://developer.android.com/guide/topics/media/camera.html
See http://developer.android.com/reference/android/hardware/Camera.html
Android Devices have cameras
}
OPTION1: CameraSimple.java callback method
when Camera Intent done
//METHOD to Get Intents Recieved --in this case when camera app done
// will put message in TextView on main apps interface if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
@Override if (resultCode == RESULT_OK) {
protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Video captured and saved to fileUri specified in the Intent
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { Toast.makeText(this, "Video saved to:\n" +
if (resultCode == RESULT_OK) {
data.getData(), Toast.LENGTH_LONG).show();
// say that we saved image } else if (resultCode == RESULT_CANCELED) {
TextView t = (TextView)findViewById(R.id.textView_Results);
t.setText("Success"); // User cancelled the video capture
} else {
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture // Video capture failed, advise user
TextView t = (TextView)findViewById(R.id.textView_Results);
}
t.setText("Camera Cancelled");
} else { }
// Image capture failed, advise user
}
TextView t = (TextView)findViewById(R.id.textView_Results);
t.setText("Failure");
}
OPTION1: CameraSimple.java
methods for getting File URL
//METHODS to handle file storage
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){ // Create a media file name
return Uri.fromFile(getOutputMediaFile(type)); String timeStamp = new
} SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
// To be safe, you should check that the SDCard is mounted mediaFile = new File(mediaStorageDir.getPath() + File.separator
+
// using Environment.getExternalStorageState() before doing this.
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
File mediaStorageDir = new
File(Environment.getExternalStoragePublicDirectory( mediaFile = new File(mediaStorageDir.getPath() + File.separator
+
Environment.DIRECTORY_PICTURES), "MyCameraApp");
"VID_"+ timeStamp + ".mp4");
// This location works best if you want the created images to be shared
} else {
// between applications and persist after your app has been uninstalled.
return null;
// Create the storage directory if it does not exist
}
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return mediaFile;
Log.d("MyCameraApp", "failed to create directory");
}
return null;
}
}
}
OPTION 1: Lets run it
OPTION 1: Running results
Suppose you want the image data
Option 1 load the Image from the File you specified
Option 2 the Intent returned from using Camera
App has a small version of the image bitmap that
was taken you can grab directly
Option 1: Loading (regular size)
image from saved File
private void setPic() {
// Get the dimensions of the View - NOTE: assumes the Activity has a ImageView object mImageView
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap NOTE: assumes mCurrentPhotoPath is location of image you took
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
//More than 1 Camera?: On devices running Android 2.3 (API Level 9) or higher, you can
access specific cameras using Camera.open(int). The example code above will access the first,
back-facing camera on a device with more than one camera.
OPTION 2: STEP 1 (optional)
check camera capabilities
using the Camera.getParameters() method and
checking the returned Camera.Parameters object
for supported capabilities.
When using API Level 9 or higher, use the
Camera.getCameraInfo() to determine if a camera
is on the front or back of the device, and the
orientation of the image.
OPTION 2: Step 2- create Preview
Interface
Users (usually) must be able to see what the device
camera sees.
SurfaceView =can display the live image data
coming from a camera
THE CODE next:
how to create basic camera preview class that can be
included in a View layout.
implements SurfaceHolder.Callback in order to capture
the callback events for creating and destroying the
view, which are needed for assigning the camera
preview input.
OPTION 2- Step 2 Preview
Interface code
public CameraPreview(Context context, Camera camera) {
package grewe.examples.Camera.InApp;
super(context);
mCamera = camera;
import android.graphics.Canvas;
import android.graphics.Rect;
// Install a SurfaceHolder.Callback so we get notified when the
import android.view.Surface;
// underlying surface is created and destroyed.
import android.view.SurfaceHolder;
mHolder = getHolder();
import android.view.SurfaceView;
mHolder.addCallback(this);
import android.hardware.Camera;
// deprecated setting, but required on Android versions prior to 3.0
import android.content.*;
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
import java.io.IOException;
}
import android.util.Log;
}
// start preview with new settings
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { try {
// If your preview can change or rotate, take care of those events here. mCamera.setPreviewDisplay(mHolder);
// Make sure to stop the preview before resizing or reformatting it. mCamera.startPreview();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(id.camera_preview);
preview.addView(mPreview);
}
OPTION 2: Step 4&5 code to do capture
---trigger and handling
set up listeners for your user interface controls to
respond to a user action by taking a picture.
Camera.takePicture() = takes picture,
3 parameters which receive data from the camera.
To get data in a JPEG format, you must implement an
Camera.PictureCallback interface to receive the image
data and write it to a file.
OPTION 2: Step 4&5 event handling
when button hit this is callback after
picture taken ---store to file
Add code to main Application Activity class
This is private variable of this class
private PictureCallback mPicture = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
OPTION2- Step 4&5 registering
event handler to a button
Trigger capturing an image by calling the
Camera.takePicture() method. The following
example code shows how to call this method from a
button View.OnClickListener.
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);//see previous page code
//callback is mPicture !!!!
}
}
);
OPTION2 Step 6 Release the
camera
Caution: Remember to release the Camera object
by calling the Camera.release() when your
application is done using it! For information about
how to release the camera, see Releasing the
camera.
OPTION 2: Steps
1) Create simple interface with a button that will
trigger taking the picture
App Interface --- button
Add button
The Main Application (Activity) class
import android.app.Activity; //loads interface stored in main.xml of layout directory
import android.content.Intent; setContentView(R.layout.main);
import android.graphics.Bitmap; Button cameraButton = (Button) findViewById(R.id.camera);
import android.net.Uri;
import android.os.Bundle; //setups button to have even so that it creates an Activity
import android.util.Log; //of instance photoshoot.class and start it as an Activity
import android.view.View; cameraButton.setOnClickListener( new OnClickListener(){
import android.view.View.OnClickListener; public void onClick(View v ){
import android.widget.Button; Intent i = new Intent(cameralab2.this, photoshoot.class);
import android.widget.ImageView; startActivityForResult(i,CAMERALAB2);
}
public class cameralab2 extends Activity { });
/** Called when the activity is first created. */
final int CAMERALAB1=1; }
final int CAMERALAB2=2; // MORE ON OTHER SLIDES
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
The Main Application (Activity) class
@Override
Here setting up the protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
onActivityResult
((ImageView)findViewById(R.id.picture)).setImageBitmap(b);
}
else if (requestCode== CAMERALAB2 && resultCode ==
Activity.RESULT_OK){
Log.v("Result","Result:"+data.toURI());
Bundle extras = data.getExtras();
String imageurl = extras.getString("url");
Uri imgUri = Uri.parse(imageurl);
((ImageView)findViewById(R.id.picture)).setImageURI(imgUri);
}
}
}
PhotoShoot class