I created a custom camera app that saves the image in SD.
I have another activity that involves an ImageView.
I want to display the photo taken from camera in ImageView.
How should I do that?
public class CameraActivity extends Activity {
private static final String TAG = "CUSTOMCAM";
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Camera mCamera;
private CameraPreview mPreview;
private SensorManager sensorManager = null;
private int orientation;
private ExifInterface exif;
private int deviceHeight;
private Button ibRetake;
private Button ibUse;
private Button ibCapture;
private FrameLayout flBtnContainer;
private File sdRoot;
private String dir;
private String fileName;
private ImageView rotatingImage;
private int degrees = -1;
private Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
// Setting all the path for the image
sdRoot = Environment.getExternalStorageDirectory();
dir = "/DCIM/Camera/";
// Getting all the needed elements from the layout
rotatingImage = (ImageView) findViewById(R.id.imageView1);
ibRetake = (Button) findViewById(R.id.ibRetake);
ibUse = (Button) findViewById(R.id.ibUse);
ibCapture = (Button) findViewById(R.id.ibCapture);
flBtnContainer = (FrameLayout) findViewById(R.id.flBtnContainer);
// Getting the sensor service.
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// Selecting the resolution of the Android device so we can create a
// proportional preview
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
deviceHeight = display.getHeight();
// Add a listener to the Capture button
ibCapture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
// Add a listener to the Retake button
ibRetake.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Deleting the image from the SD card/
File discardedPhoto = new File(sdRoot, dir + fileName);
discardedPhoto.delete();
// Restart the camera preview.
mCamera.startPreview();
// Reorganize the buttons on the screen
flBtnContainer.setVisibility(LinearLayout.VISIBLE);
ibRetake.setVisibility(LinearLayout.GONE);
ibUse.setVisibility(LinearLayout.GONE);
}
});
// Add a listener to the Use button
ibUse.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Everything is saved so we can quit the app.
finish();
Intent intent = new Intent(CameraActivity.this, PicturePreview.class);
startActivity(intent);
}
});
}
private PictureCallback mPicture = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// Replacing the button after a photho was taken.
flBtnContainer.setVisibility(View.GONE);
ibRetake.setVisibility(View.VISIBLE);
ibUse.setVisibility(View.VISIBLE);
// File name of the image that we just took.
fileName = "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()).toString() + ".jpg";
// Creating the directory where to save the image. Sadly in older
// version of Android we can not get the Media catalog name
File mkDir = new File(sdRoot, dir);
mkDir.mkdirs();
// Main file where to save the data that we recive from the camera
File pictureFile = new File(sdRoot, dir + fileName);
try {
FileOutputStream purge = new FileOutputStream(pictureFile);
purge.write(data);
purge.close();
} catch (FileNotFoundException e) {
Log.d("DG_DEBUG", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("DG_DEBUG", "Error accessing file: " + e.getMessage());
}
// Adding Exif data for the orientation. For some strange reason the
// ExifInterface class takes a string instead of a file.
try {
exif = new ExifInterface("/sdcard/" + dir + fileName);
exif.setAttribute(ExifInterface.TAG_ORIENTATION, "" + orientation);
exif.saveAttributes();
} catch (IOException e) {
e.printStackTrace();
}
//SendBroadcasts let's us instantly update the SD card with our image
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+Environment.getExternalStorageDirectory())));
}
};
private void createCamera() {
// Create an instance of Camera
mCamera = getCameraInstance();
Setting the right parameters in the camera
Camera.Parameters params = mCamera.getParameters();
mCamera.setParameters(params);
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
// Calculating the width of the preview so it is proportional.
float widthFloat = (float) (deviceHeight) * 4 / 3;
int width = Math.round(widthFloat);
// Resizing the LinearLayout so we can make a proportional preview. This
// approach is not 100% perfect because on devices with a really small
// screen the the image will still be distorted - there is place for
// improvment.
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, deviceHeight);
preview.setLayoutParams(layoutParams);
// Adding the camera preview after the FrameLayout and before the button
// as a separated element.
preview.addView(mPreview, 0);
}
#Override
protected void onResume() {
super.onResume();
// Test if there is a camera on the device and if the SD card is
// mounted.
if (!checkCameraHardware(this)) {
Intent i = new Intent(this, NoCamera.class);
startActivity(i);
finish();
} else if (!checkSDCard()) {
Intent i = new Intent(this, NoSDCard.class);
startActivity(i);
finish();
}
// Creating the camera
createCamera();
// Register this class as a listener for the accelerometer sensor
////sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
// release the camera immediately on pause event
releaseCamera();
// removing the inserted view - so when we come back to the app we
// won't have the views on top of each other.
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.removeViewAt(0);
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
private boolean checkSDCard() {
boolean state = false;
String sd = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(sd)) {
state = true;
}
return state;
}
/**
* A safe way to get an instance of the Camera object.
*/
public static Camera getCameraInstance() {
Camera c = null;
try {
// attempt to get a Camera instance
c = Camera.open();
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
// returns null if camera is unavailable
return c;
}
/**
* Putting in place a listener so we can get the sensor data only when
* something changes.
*/
public void onSensorChanged(SensorEvent event) {
synchronized (this) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
RotateAnimation animation = null;
if (event.values[0] < 4 && event.values[0] > -4) {
if (event.values[1] > 0 && orientation != ExifInterface.ORIENTATION_ROTATE_90) {
// UP
orientation = ExifInterface.ORIENTATION_ROTATE_90;
animation = getRotateAnimation(270);
degrees = 270;
} else if (event.values[1] < 0 && orientation != ExifInterface.ORIENTATION_ROTATE_270) {
// UP SIDE DOWN
orientation = ExifInterface.ORIENTATION_ROTATE_270;
animation = getRotateAnimation(90);
degrees = 90;
}
} else if (event.values[1] < 4 && event.values[1] > -4) {
if (event.values[0] > 0 && orientation != ExifInterface.ORIENTATION_NORMAL) {
// LEFT
orientation = ExifInterface.ORIENTATION_NORMAL;
animation = getRotateAnimation(0);
degrees = 0;
} else if (event.values[0] < 0 && orientation != ExifInterface.ORIENTATION_ROTATE_180) {
// RIGHT
orientation = ExifInterface.ORIENTATION_ROTATE_180;
animation = getRotateAnimation(180);
degrees = 180;
}
}
if (animation != null) {
rotatingImage.startAnimation(animation);
}
}
}
}
/**
* Calculating the degrees needed to rotate the image imposed on the button
* so it is always facing the user in the right direction
*
* #param toDegrees
* #return
*/
private RotateAnimation getRotateAnimation(float toDegrees) {
float compensation = 0;
if (Math.abs(degrees - toDegrees) > 180) {
compensation = 360;
}
// When the device is being held on the left side (default position for
// a camera) we need to add, not subtract from the toDegrees.
if (toDegrees == 0) {
compensation = -compensation;
}
// Creating the animation and the RELATIVE_TO_SELF means that he image
// will rotate on it center instead of a corner.
RotateAnimation animation = new RotateAnimation(degrees, toDegrees - compensation, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
// Adding the time needed to rotate the image
animation.setDuration(250);
// Set the animation to stop after reaching the desired position. With
// out this it would return to the original state.
animation.setFillAfter(true);
return animation;
}
/**
* STUFF THAT WE DON'T NEED BUT MUST BE HEAR FOR THE COMPILER TO BE HAPPY.
*/
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.custom_cam, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
this is the code
and then I have a second activity that I need to call the image taken
Keep the saved image path in string. Then pass it to other activity with Bundle.
eg.
In your camera activity
under your ibUse.setOnClickListener. Like this;
ibUse.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Everything is saved so we can quit the app.
finish();
Intent intent = new Intent(CameraActivity.this, PicturePreview.class);
Bundle extras = new Bundle();
extras.putString("ImagePath", path);
intent.putExtras(extras);
startActivity(intent);
}
});
In your preview activity under onCreate method
Bundle bundle = getIntent().getExtras();
String path = bundle.getString("ImagePath");
ImageView image = (ImageView) findViewById(R.id.image);
File imgFile = new File(path);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
image.setImageBitmap(myBitmap);
}
Related
I am working on Camera related app. I have successfully completed capturing photo and photo preview also. But one issue arised. When I take photo, photo Capture is successful but preview is being inverse. I have tried so many solutions from stack overflow though luck did not favor for me so far.
My Camera Preview class is:
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
private Context mContext;
public CameraPreview(Context context, Camera camera) {
super(context);
mContext = context;
mCamera = camera;
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
try {
// create the surface and start camera preview
if (mCamera == null) {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}
} catch (IOException e) {
Log.d(VIEW_LOG_TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void refreshCamera(Camera camera) {
if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
setCamera(camera);
// TODO: don't hardcode cameraId '0' here... figure this out later.
setCameraDisplayOrientation(mContext, Camera.CameraInfo.CAMERA_FACING_BACK, mCamera);
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
Log.d(VIEW_LOG_TAG, "Error starting camera preview: " + e.getMessage());
}
}
public static void setCameraDisplayOrientation(Context context, int cameraId, Camera camera) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
int rotation = wm.getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
// Compensate for the mirror image.
result = (360 - result) % 360;
} else {
// Back-facing camera.
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
refreshCamera(mCamera);
}
public void setCamera(Camera camera) {
//method to set a camera instance
mCamera = camera;
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
// mCamera.release();
}
}
and my PhotoCaputeActivity class is below:
public class PhotoCaptureActivity extends AppCompatActivity {
private static final String TAG = "PhotoCaptureActivity";
//Arraylist for image timer animation
int[] imageArray = {R.drawable.ic_five_128, R.drawable.ic_four_128,
R.drawable.ic_three_128, R.drawable.ic_two_128, R.drawable.ic_one_128,
R.drawable.ic_smiley_128
};
int i = 0;
private final static int DELAY = 1000;
private final Handler handler = new Handler();
Timer timer = new Timer();
Thread timerThread;
// Create variable to handle progress and set it to 0.
private int progress = 0;
Bitmap bitmap,photoCaptureBitmap;
private Camera mCamera;
private CameraPreview mPreview;
private PictureCallback mPicture;
private ImageButton capture, switchCamera;
private Context myContext;
private LinearLayout cameraPreview;
private boolean cameraFront = false;
private ImageView capturedImageHolder;
private ProgressBar progressBar_take_photo;
ImageButton next_button_take_photo;
ImageButton back_button_take_photo;
TextView photo_title_text;
ImageView image_animation;
private MyPreferences myPreferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowTitleEnabled(false);
setContentView(R.layout.photo_capture_activity);
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Logger.addLogAdapter(new AndroidLogAdapter());
myContext = this;
initialize();
myPreferences = MyPreferences.getPreferences(this);
nextButton();
backButton();
progressBar();
nameTextShow();
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
cameraFront = true;
break;
}
}
return cameraId;
}
private int findBackFacingCamera() {
int cameraId = -1;
//Search for the back facing camera
//get the number of cameras
int numberOfCameras = Camera.getNumberOfCameras();
//for every camera check
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
cameraFront = false;
break;
}
}
return cameraId;
}
public void onResume() {
super.onResume();
if (!hasCamera(myContext)) {
Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
toast.show();
finish();
}
if (mCamera == null) {
//if the front facing camera does not exist
if (findFrontFacingCamera() < 0) {
//Toast.makeText(this, "", Toast.LENGTH_LONG).show();
//switchCamera.setVisibility(View.GONE);
}
mCamera = Camera.open(findFrontFacingCamera());
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}else{
//Visibility
cameraPreview.setVisibility(View.GONE);
capturedImageHolder.setVisibility(View.VISIBLE);
String photoCapturePreview = myPreferences.getVisitorPhoto();
if(!photoCapturePreview.equals("")) {
photoCaptureBitmap = decodeToBase64(photoCapturePreview);
}
capturedImageHolder.setImageBitmap(photoCaptureBitmap);
}
}
public static Bitmap decodeToBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
// Code for initialization
public void initialize() {
cameraPreview = (LinearLayout) findViewById(R.id.cameraFrame);
mPreview = new CameraPreview(myContext, mCamera);
cameraPreview.addView(mPreview);
capture = (ImageButton) findViewById(R.id.button_capture);
capture.setOnClickListener(captrureListener);
//switchCamera = (Button) findViewById(R.id.button_ChangeCamera);
//switchCamera.setOnClickListener(switchCameraListener);
image_animation = (ImageView) findViewById(R.id.timer_text);
capturedImageHolder = (ImageView) findViewById(R.id.captured_image);
next_button_take_photo = (ImageButton) findViewById(R.id.next_button_take_photo);
back_button_take_photo = (ImageButton) findViewById(R.id.back_button_take_photo);
progressBar_take_photo = (ProgressBar) findViewById(R.id.progressBar_take_photo);
photo_title_text = (TextView) findViewById(R.id.photo_title_text);
}
//Next Button operation based on mobile number input
private void nextButton() {
next_button_take_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideKeyboard();
if (bitmap != null) {
Intent newIntent = new Intent(getApplicationContext(), ConfirmationActivity.class);
startActivity(newIntent);
}
}
});
}
//Back button operation
private void backButton() {
back_button_take_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent newIntent = new Intent(getApplicationContext(), AddressInputActivity.class);
startActivity(newIntent);
}
});
}
//Progress bar operation
private void progressBar() {
//simpleProgressBar.setMax(100); // 100 maximum value for the progress value
//simpleProgressBar.setProgress(50); // 50 default progress value for the progress bar
// Get the Drawable custom_progressbar
//Drawable draw=res.getDrawable(R.drawable.custom_progressbar);
// set the drawable as progress drawable
//progressBar.setProgressDrawable(draw);
}
//Normal text show
private void nameTextShow() {
String vsitorName = myPreferences.getVisitorName();
photo_title_text.setText(vsitorName + ", please smile for the Camera");
}
OnClickListener switchCameraListener = new OnClickListener() {
#Override
public void onClick(View v) {
//get the number of cameras
int camerasNumber = Camera.getNumberOfCameras();
if (camerasNumber > 1) {
//release the old camera instance
//switch camera, from the front and the back and vice versa
releaseCamera();
chooseCamera();
} else {
Toast toast = Toast.makeText(myContext, "Sorry, your phone has only one camera!", Toast.LENGTH_LONG);
toast.show();
}
}
};
public void chooseCamera() {
//if the camera preview is the front
if (cameraFront) {
int cameraId = findBackFacingCamera();
if (cameraId >= 0) {
//open the backFacingCamera
//set a picture callback
//refresh the preview
mCamera = Camera.open(cameraId);
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
} else {
int cameraId = findFrontFacingCamera();
if (cameraId >= 0) {
//open the backFacingCamera
//set a picture callback
//refresh the preview
mCamera = Camera.open(cameraId);
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
}
}
#Override
protected void onPause() {
super.onPause();
//when on Pause, release camera in order to be used from other applications
releaseCamera();
}
private boolean hasCamera(Context context) {
//check if the device has camera
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
return true;
} else {
return false;
}
}
private PictureCallback getPictureCallback() {
PictureCallback picture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
if (data != null) {
//make a new picture file
File pictureFile = getOutputMediaFile();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
String imageEncoded = Base64.encodeToString(data, Base64.DEFAULT);
myPreferences.setVisitorPhoto(imageEncoded);
if (bitmap == null) {
return;
}
try {
//write the file
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
//Toast toast = Toast.makeText(myContext, "Picture saved: " + pictureFile.getName(), Toast.LENGTH_LONG);
//toast.show();
//Method for image view
captureImageView();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
//refresh camera to continue preview
mPreview.refreshCamera(mCamera);
}
}
};
return picture;
}
**private void captureImageView(){
//Visibitlity of camera photo
cameraPreview.setVisibility(View.GONE);
capturedImageHolder.setVisibility(View.VISIBLE);
int screenWidth = getResources().getDisplayMetrics().widthPixels;
int screenHeight = getResources().getDisplayMetrics().heightPixels;
Camera.CameraInfo info = new Camera.CameraInfo();
Matrix mtx = new Matrix();
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
// Notice that width and height are reversed
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, screenHeight, screenWidth, true);
int w = scaled.getWidth();
int h = scaled.getHeight();
// Perform matrix rotations/mirrors depending on camera that took the photo
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT)
{
float[] mirrorY = { -1, 0, 0, 0, 1, 0, 0, 0, 1};
Matrix matrixMirrorY = new Matrix();
matrixMirrorY.setValues(mirrorY);
mtx.postConcat(matrixMirrorY);
}
// Setting post rotate to 90
mtx.postRotate(270);
// Rotating Bitmap
bitmap = Bitmap.createBitmap(scaled, 0, 0, w, h, mtx, true);
//capturedImageHolder.setImageBitmap(bitmap);
capturedImageHolder.setImageBitmap(scaleDownBitmapImage(bitmap, 350, 450));
}else{// LANDSCAPE MODE
//No need to reverse width and height
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, screenWidth,screenHeight , true);
bitmap=scaled;
//capturedImageHolder.setImageBitmap(bitmap);
capturedImageHolder.setImageBitmap(scaleDownBitmapImage(bitmap, 650, 300));
}
}**
private Bitmap scaleDownBitmapImage(Bitmap bitmap, int newWidth, int newHeight) {
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
return resizedBitmap;
}
OnClickListener captrureListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Visibitlity of camera photo
cameraPreview.setVisibility(View.VISIBLE);
capturedImageHolder.setVisibility(View.GONE);
new Loading().execute();
//timer.schedule(task, DELAY, DELAY);
timerThread = new Thread()
{
public void run() {
for (i = 0; i < 6; i++) {
runOnUiThread(new Runnable() {
public void run() {
image_animation.setImageResource(imageArray[i]);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(i==6){
timerThread.interrupt();
}
}
}
};
timerThread.start();
}
};
private final TimerTask task = new TimerTask() {
private int counter = 0;
public void run() {
handler.post(new Runnable() {
public void run() {
image_animation.setImageResource(imageArray[i]);
i++;
if (i > imageArray.length - 1) {
i = 0;
}
}
});
if (++counter == 6) {
timer.cancel();
timer.purge();
}
}
};
public class Loading extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// 6000ms=6s at intervals of 1000ms=1s so that means it lasts 5 seconds
new CountDownTimer(5000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
// every time 1 second passes
//tv.setText("" + millisUntilFinished/1000);
/* image_animation.setImageResource(imageArray[i]);
i++;
if (i > imageArray.length - 1) {
i = 0;
}*/
}
#Override
public void onFinish() {
// count finished
//tv.setText("Picture Taken");
mCamera.takePicture(null, null, null, mPicture);
}
}.start();
}
}
//make picture and save to a folder
private static File getOutputMediaFile() {
//make a new file directory inside the "sdcard" folder
File mediaStorageDir = new File("/sdcard/", "JCG Camera");
//if this "JCGCamera folder does not exist
if (!mediaStorageDir.exists()) {
//if you cannot make this folder return
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
//take the current timeStamp
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
//and make a media file:
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
private void releaseCamera() {
// stop and release camera
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
private void hideKeyboard() {
View view = getCurrentFocus();
if (view != null) {
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
#Override
public void onBackPressed()
{
// code here to show dialog
super.onBackPressed(); // optional depending on your needs
}
#Override
protected void onDestroy() {
if (mCamera != null) {
mCamera.release();
}
super.onDestroy();
}
#Override
public void onStop() {
if (mCamera != null) {
mCamera.release();
}
super.onStop();
}
}
What is the result I am getting right now and what I want that is below. Please see during photo capture hand was in the right side but when photo preview is displaying it is showing in the left hand side.
So, what can be done to resolve the issue?
Unfortunately we can not disable mirror preview but we can use TextureView and apply SetTransform to reverse Camera Preview, this work only with API >= 14 . so try below code in your PhotoCaputeActivity
mCamera.setDisplayOrientation(90);
Matrix matrix = new Matrix();
matrix.setScale(-1, 1);
matrix.postTranslate(width, 0);
mTextureView.setTransform(matrix);
for more info check this link.
Also keep in mind
This is used with Front camera and when trying with Back camera make mTextureView.setTransform(null);
At last I got solution by adding following attributes in the imageview and worked like a charm :)
android:scaleX="-1"
in OpenCV JavaCameraView, it is very easy
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
imageMat = inputFrame.rgba().t();
if (//horizontal reverse)
Core.flip(imageMat, imageMat, 1);
else //for vertical reverse
Core.flip(imageMat, imageMat, -1);
I got a RA application using Camera API and I want to integrate Camera2.
Is an equivalent exists to get each preview frame in order to sent it to JMonkeyEngine ?
Here is my code using Camera API :
public void onResume() {
mStopPreview = false;
try {
mCamera = CameraOldManager.getCamera();
if (mCamera != null) {
// initialize camera parameters
CameraOldManager.initializeCameraParameters(mCameraWidth, mCameraHeight);
CameraOldManager.setCameraDisplayOrientation(mActivity, 0, mCamera);
preparePreviewCallbackBuffer();
mJmeApp.setCameraVideoResolution(mCameraWidth, mCameraHeight);
mPreview = new CameraPreview(mActivity, mCamera, mCameraCallback);
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(1, 1);
mActivity.addContentView(mPreview, lp);
}
} catch (Exception e) {
Log.e(TAG, "Exception init camera: " + e.getMessage());
}
}
// prepares the Camera preview callback buffers.
public void preparePreviewCallbackBuffer() {
int pformat;
pformat = mCamera.getParameters().getPreviewFormat();
Log.e(TAG, "PREVIEW format: " + pformat);
// Get pixel format information to compute buffer size.
PixelFormat info = new PixelFormat();
PixelFormat.getPixelFormatInfo(pformat, info);
// The actual preview width and height.
// They can differ from the requested width mDesiredmCameraWidth
//mPreviewWidth = mCamera.getParameters().getPreviewSize().width;
//mPreviewHeight = mCamera.getParameters().getPreviewSize().height;
int bufferSizeRGB565 = mCameraWidth * mCameraHeight * 2 + 4096;
//Delete buffer before creating a new one.
mPreviewBufferRGB565 = null;
mPreviewBufferRGB565 = new byte[bufferSizeRGB565];
mPreviewByteBufferRGB565 = ByteBuffer.allocateDirect(mPreviewBufferRGB565.length);
mCameraJMEImageRGB565 = new Image(Image.Format.RGB565, mCameraWidth,
mCameraHeight, mPreviewByteBufferRGB565);
}
// Implement the interface for getting copies of preview frames
private final Camera.PreviewCallback mCameraCallback = new Camera.PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera c) {
if (c != null && !mStopPreview && mJmeApp != null && mJmeApp.isFirstModelLoaded()) {
mPreviewByteBufferRGB565.clear();
// Perform processing on the camera preview data.
if (mPixelFormatConversionNeeded) {
RAUtils.yCbCrToRGB565(data, mCameraWidth, mCameraHeight,
mPreviewBufferRGB565);
mPreviewByteBufferRGB565.put(mPreviewBufferRGB565);
} else {
mPreviewByteBufferRGB565.put(data);
}
mCameraJMEImageRGB565.setData(mPreviewByteBufferRGB565);
mJmeApp.setVideoBGTexture(mCameraJMEImageRGB565);
}
}
};
What I need is to get frames to give them to JME.
I have a project that captures an image using OpenCV's CamerabridgeViewBase and another project that detects a pingpong ball. The problem is I can't combine those two projects. What I want is to capture a live feed, then return a single image that already has a detection in it.
Here are the classes of the project that can capture an image and store it in the gallery:
public final class MainActivity extends ActionBarActivity
implements CvCameraViewListener2 {
// A tag for log output.
private static final String TAG =
MainActivity.class.getSimpleName();
// A key for storing the index of the active camera.
private static final String STATE_CAMERA_INDEX = "cameraIndex";
// A key for storing the index of the active image size.
private static final String STATE_IMAGE_SIZE_INDEX =
"imageSizeIndex";
// An ID for items in the image size submenu.
private static final int MENU_GROUP_ID_SIZE = 2;
// The index of the active camera.
private int mCameraIndex;
// The index of the active image size.
private int mImageSizeIndex;
// Whether the active camera is front-facing.
// If so, the camera view should be mirrored.
private boolean mIsCameraFrontFacing;
// The number of cameras on the device.
private int mNumCameras;
// The image sizes supported by the active camera.
private List<Size> mSupportedImageSizes;
// The camera view.
private CameraBridgeViewBase mCameraView;
// Whether the next camera frame should be saved as a photo.
private boolean mIsPhotoPending;
// A matrix that is used when saving photos.
private Mat mBgr;
// Whether an asynchronous menu action is in progress.
// If so, menu interaction should be disabled.
private boolean mIsMenuLocked;
// The OpenCV loader callback.
private BaseLoaderCallback mLoaderCallback =
new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(final int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
Log.d(TAG, "OpenCV loaded successfully");
mCameraView.enableView();
//mCameraView.enableFpsMeter();
mBgr = new Mat();
break;
default:
super.onManagerConnected(status);
break;
}
}
};
// Suppress backward incompatibility errors because we provide
// backward-compatible fallbacks.
#SuppressLint("NewApi")
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Window window = getWindow();
window.addFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (savedInstanceState != null) {
mCameraIndex = savedInstanceState.getInt(
STATE_CAMERA_INDEX, 0);
mImageSizeIndex = savedInstanceState.getInt(
STATE_IMAGE_SIZE_INDEX, 0);
} else {
mCameraIndex = 0;
mImageSizeIndex = 0;
}
final Camera camera;
if (Build.VERSION.SDK_INT >=
Build.VERSION_CODES.GINGERBREAD) {
CameraInfo cameraInfo = new CameraInfo();
Camera.getCameraInfo(mCameraIndex, cameraInfo);
mIsCameraFrontFacing =
(cameraInfo.facing ==
CameraInfo.CAMERA_FACING_FRONT);
mNumCameras = Camera.getNumberOfCameras();
camera = Camera.open(mCameraIndex);
} else { // pre-Gingerbread
// Assume there is only 1 camera and it is rear-facing.
mIsCameraFrontFacing = false;
mNumCameras = 1;
camera = Camera.open();
}
final Parameters parameters = camera.getParameters();
camera.release();
mSupportedImageSizes =
parameters.getSupportedPreviewSizes();
final Size size = mSupportedImageSizes.get(mImageSizeIndex);
mCameraView = new JavaCameraView(this, mCameraIndex);
mCameraView.setMaxFrameSize(size.width, size.height);
mCameraView.setCvCameraViewListener(this);
setContentView(mCameraView);
}
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the current camera index.
savedInstanceState.putInt(STATE_CAMERA_INDEX, mCameraIndex);
// Save the current image size index.
savedInstanceState.putInt(STATE_IMAGE_SIZE_INDEX,
mImageSizeIndex);
super.onSaveInstanceState(savedInstanceState);
}
// Suppress backward incompatibility errors because we provide
// backward-compatible fallbacks.
#SuppressLint("NewApi")
#Override
public void recreate() {
if (Build.VERSION.SDK_INT >=
Build.VERSION_CODES.HONEYCOMB) {
super.recreate();
} else {
finish();
startActivity(getIntent());
}
}
#Override
public void onPause() {
if (mCameraView != null) {
mCameraView.disableView();
}
super.onPause();
}
#Override
public void onResume() {
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0,
this, mLoaderCallback);
mIsMenuLocked = false;
}
#Override
public void onDestroy() {
if (mCameraView != null) {
mCameraView.disableView();
}
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
if (mNumCameras < 2) {
// Remove the option to switch cameras, since there is
// only 1.
menu.removeItem(R.id.menu_next_camera);
}
int numSupportedImageSizes = mSupportedImageSizes.size();
if (numSupportedImageSizes > 1) {
final SubMenu sizeSubMenu = menu.addSubMenu(
R.string.menu_image_size);
for (int i = 0; i < numSupportedImageSizes; i++) {
final Size size = mSupportedImageSizes.get(i);
sizeSubMenu.add(MENU_GROUP_ID_SIZE, i, Menu.NONE,
String.format("%dx%d", size.width,
size.height));
}
}
return true;
}
// Suppress backward incompatibility errors because we provide
// backward-compatible fallbacks (for recreate).
#SuppressLint("NewApi")
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (mIsMenuLocked) {
return true;
}
if (item.getGroupId() == MENU_GROUP_ID_SIZE) {
mImageSizeIndex = item.getItemId();
recreate();
return true;
}
switch (item.getItemId()) {
case R.id.menu_next_camera:
mIsMenuLocked = true;
// With another camera index, recreate the activity.
mCameraIndex++;
if (mCameraIndex == mNumCameras) {
mCameraIndex = 0;
}
mImageSizeIndex = 0;
recreate();
return true;
case R.id.menu_take_photo:
mIsMenuLocked = true;
// Next frame, take the photo.
mIsPhotoPending = true;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCameraViewStarted(final int width,
final int height) {
}
#Override
public void onCameraViewStopped() {
}
#Override
public Mat onCameraFrame(final CvCameraViewFrame inputFrame) {
final Mat rgba = inputFrame.rgba();
if (mIsPhotoPending) {
mIsPhotoPending = false;
takePhoto(rgba);
}
if (mIsCameraFrontFacing) {
// Mirror (horizontally flip) the preview.
Core.flip(rgba, rgba, 1);
}
return rgba;
}
private void takePhoto(final Mat rgba) {
// Determine the path and metadata for the photo.
final long currentTimeMillis = System.currentTimeMillis();
final String appName = getString(R.string.app_name);
final String galleryPath =
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).toString();
final String albumPath = galleryPath + File.separator +
appName;
final String photoPath = albumPath + File.separator +
currentTimeMillis + LabActivity.PHOTO_FILE_EXTENSION;
final ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, photoPath);
values.put(Images.Media.MIME_TYPE,
LabActivity.PHOTO_MIME_TYPE);
values.put(Images.Media.TITLE, appName);
values.put(Images.Media.DESCRIPTION, appName);
values.put(Images.Media.DATE_TAKEN, currentTimeMillis);
// Ensure that the album directory exists.
File album = new File(albumPath);
if (!album.isDirectory() && !album.mkdirs()) {
Log.e(TAG, "Failed to create album directory at " +
albumPath);
onTakePhotoFailed();
return;
}
// Try to create the photo.
Imgproc.cvtColor(rgba, mBgr, Imgproc.COLOR_RGBA2BGR, 3);
if (!Imgcodecs.imwrite(photoPath, mBgr)) {
Log.e(TAG, "Failed to save photo to " + photoPath);
onTakePhotoFailed();
}
Log.d(TAG, "Photo saved successfully to " + photoPath);
// Try to insert the photo into the MediaStore.
Uri uri;
try {
uri = getContentResolver().insert(
Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (final Exception e) {
Log.e(TAG, "Failed to insert photo into MediaStore");
e.printStackTrace();
// Since the insertion failed, delete the photo.
File photo = new File(photoPath);
if (!photo.delete()) {
Log.e(TAG, "Failed to delete non-inserted photo");
}
onTakePhotoFailed();
return;
}
// Open the photo in LabActivity.
final Intent intent = new Intent(this, LabActivity.class);
intent.putExtra(LabActivity.EXTRA_PHOTO_URI, uri);
intent.putExtra(LabActivity.EXTRA_PHOTO_DATA_PATH,
photoPath);
runOnUiThread(new Runnable() {
#Override
public void run() {
startActivity(intent);
}
});
}
private void onTakePhotoFailed() {
mIsMenuLocked = false;
// Show an error message.
final String errorMessage =
getString(R.string.photo_error_message);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, errorMessage,
Toast.LENGTH_SHORT).show();
}
});
}
--
public final class LabActivity extends ActionBarActivity {
public static final String PHOTO_FILE_EXTENSION = ".png";
public static final String PHOTO_MIME_TYPE = "image/png";
public static final String EXTRA_PHOTO_URI =
"com.nummist.secondsight.LabActivity.extra.PHOTO_URI";
public static final String EXTRA_PHOTO_DATA_PATH =
"com.nummist.secondsight.LabActivity.extra.PHOTO_DATA_PATH";
private Uri mUri;
private String mDataPath;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
mUri = intent.getParcelableExtra(EXTRA_PHOTO_URI);
mDataPath = intent.getStringExtra(EXTRA_PHOTO_DATA_PATH);
final ImageView imageView = new ImageView(this);
imageView.setImageURI(mUri);
setContentView(imageView);
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.activity_lab, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete:
deletePhoto();
return true;
case R.id.menu_edit:
editPhoto();
return true;
case R.id.menu_share:
sharePhoto();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/*
* Show a confirmation dialog. On confirmation ("Delete"), the
* photo is deleted and the activity finishes.
*/
private void deletePhoto() {
final AlertDialog.Builder alert = new AlertDialog.Builder(
LabActivity.this);
alert.setTitle(R.string.photo_delete_prompt_title);
alert.setMessage(R.string.photo_delete_prompt_message);
alert.setCancelable(false);
alert.setPositiveButton(R.string.delete,
new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface dialog,
final int which) {
getContentResolver().delete(
Images.Media.EXTERNAL_CONTENT_URI,
MediaStore.MediaColumns.DATA + "=?",
new String[] { mDataPath });
finish();
}
});
alert.setNegativeButton(android.R.string.cancel, null);
alert.show();
}
/*
* Show a chooser so that the user may pick an app for editing
* the photo.
*/
private void editPhoto() {
final Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setDataAndType(mUri, PHOTO_MIME_TYPE);
startActivity(Intent.createChooser(intent,
getString(R.string.photo_edit_chooser_title)));
}
/*
* Show a chooser so that the user may pick an app for sending
* the photo.
*/
private void sharePhoto() {
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(PHOTO_MIME_TYPE);
intent.putExtra(Intent.EXTRA_STREAM, mUri);
intent.putExtra(Intent.EXTRA_SUBJECT,
getString(R.string.photo_send_extra_subject));
intent.putExtra(Intent.EXTRA_TEXT,
getString(R.string.photo_send_extra_text));
startActivity(Intent.createChooser(intent,
getString(R.string.photo_send_chooser_title)));
}
}
And here are the classes of the pingpong ball detection project:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "ObjTrackActivity";
private MenuItem mItemPreviewRGBA;
private MenuItem mItemPreviewTresholded;
public static boolean bShowTresholded = false;
public MainActivity() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate");
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(new ObjTrackViewer(this));
}
public boolean onCreateOptionsMenu(Menu menu){
Log.i(TAG, "onCreateOptionsMenu");
mItemPreviewRGBA = menu.add("Preview RGBA");
mItemPreviewTresholded = menu.add("Preview Thresholded");
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
Log.i(TAG, "Menu Item selected " + item);
if (item == mItemPreviewRGBA)
bShowTresholded = false;
else if (item == mItemPreviewTresholded)
bShowTresholded = true;
return true;
}
}
--
public class ObjTrackViewer extends SampleViewBase {
private int mFrameSize;
private Bitmap mBitmap;
private int[] mRGBA;
public ObjTrackViewer(Context context) {
super(context);
}
#Override
protected void onPreviewStared(int previewWidtd, int previewHeight) {
mFrameSize = previewWidtd * previewHeight;
mRGBA = new int[mFrameSize];
mBitmap = Bitmap.createBitmap(previewWidtd, previewHeight, Bitmap.Config.ARGB_8888);
}
#Override
protected void onPreviewStopped() {
if(mBitmap != null) {
mBitmap.recycle();
mBitmap = null;
}
mRGBA = null;
}
#Override
protected Bitmap processFrame(byte[] data) {
int[] rgba = mRGBA;
CircleObjectTrack(getFrameWidth(), getFrameHeight(), data, rgba, MainActivity.bShowTresholded);
Bitmap bmp = mBitmap;
bmp.setPixels(rgba, 0/* offset */, getFrameWidth() /* stride */, 0, 0, getFrameWidth(), getFrameHeight());
return bmp;
}
public native void CircleObjectTrack(int width, int height, byte yuv[], int[] rgba, boolean debug);
static {
System.loadLibrary("objtrack_opencv_jni");
}
}
--
public abstract class SampleViewBase extends SurfaceView implements SurfaceHolder.Callback, Runnable {
private static final String TAG = "Sample::SurfaceView";
private Camera mCamera;
private SurfaceHolder mHolder;
private int mFrameWidth;
private int mFrameHeight;
private byte[] mFrame;
private boolean mThreadRun;
private byte[] mBuffer;
public SampleViewBase(Context context) {
super(context);
mHolder = getHolder();
mHolder.addCallback(this);
Log.i(TAG, "Instantiated new " + this.getClass());
}
public int getFrameWidth() {
return mFrameWidth;
}
public int getFrameHeight() {
return mFrameHeight;
}
public void setPreview() throws IOException {
//if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
// mCamera.setPreviewTexture( new SurfaceTexture(10) );
//else
mCamera.setPreviewDisplay(null);
}
public void surfaceChanged(SurfaceHolder _holder, int format, int width, int height) {
Log.i(TAG, "surfaceCreated");
if (mCamera != null) {
Camera.Parameters params = mCamera.getParameters();
List<Camera.Size> sizes = params.getSupportedPreviewSizes();
mFrameWidth = width;
mFrameHeight = height;
// selecting optimal camera preview size
{
int minDiff = Integer.MAX_VALUE;
for (Camera.Size size : sizes) {
if (Math.abs(size.height - height) < minDiff) {
mFrameWidth = size.width;
mFrameHeight = size.height;
minDiff = Math.abs(size.height - height);
}
}
}
params.setPreviewSize(getFrameWidth(), getFrameHeight());
List<String> FocusModes = params.getSupportedFocusModes();
if (FocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO))
{
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
mCamera.setParameters(params);
/* Now allocate the buffer */
params = mCamera.getParameters();
int size = params.getPreviewSize().width * params.getPreviewSize().height;
size = size * ImageFormat.getBitsPerPixel(params.getPreviewFormat()) / 8;
mBuffer = new byte[size];
/* The buffer where the current frame will be coppied */
mFrame = new byte [size];
mCamera.addCallbackBuffer(mBuffer);
try {
setPreview();
} catch (IOException e) {
Log.e(TAG, "mCamera.setPreviewDisplay/setPreviewTexture fails: " + e);
}
/* Notify that the preview is about to be started and deliver preview size */
onPreviewStared(params.getPreviewSize().width, params.getPreviewSize().height);
/* Now we can start a preview */
mCamera.startPreview();
}
}
public void surfaceCreated(SurfaceHolder holder) {
Log.i(TAG, "surfaceCreated");
mCamera = Camera.open();
mCamera.setPreviewCallbackWithBuffer(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
synchronized (SampleViewBase.this) {
System.arraycopy(data, 0, mFrame, 0, data.length);
SampleViewBase.this.notify();
}
camera.addCallbackBuffer(mBuffer);
}
});
(new Thread(this)).start();
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.i(TAG, "surfaceDestroyed");
mThreadRun = false;
if (mCamera != null) {
synchronized (this) {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
}
onPreviewStopped();
}
/* The bitmap returned by this method shall be owned by the child and released in onPreviewStopped() */
protected abstract Bitmap processFrame(byte[] data);
/**
* This method is called when the preview process is beeing started. It is called before the first frame delivered and processFrame is called
* It is called with the width and height parameters of the preview process. It can be used to prepare the data needed during the frame processing.
* #param previewWidth - the width of the preview frames that will be delivered via processFrame
* #param previewHeight - the height of the preview frames that will be delivered via processFrame
*/
protected abstract void onPreviewStared(int previewWidtd, int previewHeight);
/**
* This method is called when preview is stopped. When this method is called the preview stopped and all the processing of frames already completed.
* If the Bitmap object returned via processFrame is cached - it is a good time to recycle it.
* Any other resourcses used during the preview can be released.
*/
protected abstract void onPreviewStopped();
public void run() {
mThreadRun = true;
Log.i(TAG, "Starting processing thread");
while (mThreadRun) {
Bitmap bmp = null;
synchronized (this) {
try {
this.wait();
bmp = processFrame(mFrame);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (bmp != null) {
Canvas canvas = mHolder.lockCanvas();
if (canvas != null) {
canvas.drawBitmap(bmp, (canvas.getWidth() - getFrameWidth()) / 2, (canvas.getHeight() - getFrameHeight()) / 2, null);
mHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}
I have tried a lot of examples but i dnt get any output.
Please tell me to change the cameraview from back to front and front to back. I don't know how to do this thing.
My Codings is shown below
My VideoActivity
public class VideoView extends Activity implements OnClickListener {
private Camera cameraObject;
private MyCameraSurfaceView myCameraSurfaceView;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
private static final String IMAGE_DIRECTORY_NAME = "VideoView";
protected static final String TAG = null;
public static final int MEDIA_TYPE_VIDEO = 2;
static Uri fileUri;
SurfaceHolder surfaceHolder;
static String picture, video, timestamp, Title;
static String play = "video";
private static int RESULT_LOAD_IMAGE = 1;
private MediaRecorder mMediaRecorder;
boolean isRecording;
static ArrayList<String> userlist;
Context context;
private long startTime = 0L;
private Handler customHandler = new Handler();;
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
TextView clicked, gallary, takephoto, camerafront, cameraback, videoview,
audioview, tbtn, capturecamera, timerValue, cam;
FrameLayout preview;
RatingBar ratings;
AlertDialog.Builder builder1;
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("" + mins + ":" + String.format("%02d", secs)
+ ":" + String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
}
};
static boolean val = false;
public static Camera isCameraAvailiable() {
Camera object = null;
try {
object = Camera.open();// default back facing camera
System.out.println("Camera object default back facing camera");
} catch (Exception e) {
e.printStackTrace();
System.out.println("Camera object");
}
return object;
}
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isRecording = false;
setContentView(R.layout.activity_video_view);
cameraObject = isCameraAvailiable();
preview = (FrameLayout) findViewById(R.id.imageview);
clicked = (TextView) findViewById(R.id.done);
gallary = (TextView) findViewById(R.id.image);
capturecamera = (TextView) findViewById(R.id.camera);
camerafront = (TextView) findViewById(R.id.fonrt);
cameraback = (TextView) findViewById(R.id.back);
videoview = (TextView) findViewById(R.id.video);
audioview = (TextView) findViewById(R.id.audio);
tbtn = (TextView) findViewById(R.id.t);
ratings = (RatingBar) findViewById(R.id.ratingBar1);
timerValue = (TextView) findViewById(R.id.timerValue);
cam = (TextView) findViewById(R.id.flipcam);
// cameraObject = isCameraAvailiable();
// mMediaRecorder = new MediaRecorder();
myCameraSurfaceView = new MyCameraSurfaceView(this, cameraObject);
// showCamera = new ShowCamera(this, cameraObject);
preview.addView(myCameraSurfaceView);
tbtn.setOnClickListener(this);
userlist = new ArrayList<String>();
// showCamera = new ShowCamera(this, cameraObject);
// preview.addView(showCamera);
videoview.setOnClickListener(this);
capturecamera.setOnClickListener(this);
cam.setOnClickListener(this);
}
#SuppressLint("NewApi") #Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.video:
System.out.println("video ### prepareVideoRecorder***");
if (isRecording) {
// stop recording and release camera
mMediaRecorder.stop();
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);// stop the
// recording
releaseMediaRecorder(); // release the MediaRecorder object
// cameraObject.lock(); // take camera access back from
// MediaRecorder
System.out.println("-----isRecording----");
// inform the user that recording has stopped
// setText("Capture");
Toast.makeText(getApplicationContext(), "Capture",
Toast.LENGTH_SHORT).show();
isRecording = false;
} else {
// initialize video camera
releaseCamera();
if (!prepareVideoRecorder()) {
// Camera is available and unlocked, MediaRecorder is
// prepared,
// now you can start recording
finish();
System.out
.println(" ### if (prepareVideoRecorder()now you can start recording)***");
// inform the user that recording has started
// setCaptureButtonText("Stop");
Toast.makeText(getApplicationContext(), "Stop",
Toast.LENGTH_SHORT).show();
isRecording = true;
System.out.println("-----prepareVideoRecorder----");
} /*
* else { // prepare didn't work, release the camera
* releaseMediaRecorder();
*/
mMediaRecorder.start();
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
isRecording = true;
// videoview.setText("STOP");
Toast.makeText(getApplicationContext(), "recording started",
Toast.LENGTH_SHORT).show();
System.out.println("----- mMediaRecorder.start();----");
// inform user
}
case R.id.flipcam: {
try {
cameraObject.stopPreview();
preview.removeView(myCameraSurfaceView);
cameraObject.release();
cameraObject = Camera.open(1);
myCameraSurfaceView = new MyCameraSurfaceView(VideoView.this,
cameraObject);
preview.addView(myCameraSurfaceView);
} catch (Exception e) {
e.printStackTrace();
}
}
default:
break;
}
}
/** A safe way to get an instance of the Camera object. */
private boolean prepareVideoRecorder() {
System.out.println(" ###method prepareVideoRecorder***");
cameraObject = isCameraAvailiable();
mMediaRecorder = new MediaRecorder();
cameraObject.unlock();
mMediaRecorder.setCamera(cameraObject);
// Step 2: Set sources
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
System.out.println("Step 2: Set sources");
// Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
mMediaRecorder.setProfile(CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH));
// mMediaRecorder.setOutputFile("/sdcard/Pictures/BusinessCard/BusinessCard.mp4");
System.out
.println("Step 3: Set a CamcorderProfile (requires API Level 8 or higher)");
// Step 4: Set output file
mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO)
.toString());
System.out.println("Step 4: Set output file");
// Step 5: Set the preview output
mMediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder()
.getSurface());
System.out.println("Step 5: Set the preview output");
// Step 6: Prepare configured MediaRecorder
System.out.println("Step 6: Prepare configured MediaRecorder");
try {
mMediaRecorder.prepare();
System.out.println("mMediaRecorder.prepare");
} catch (IllegalStateException e) {
Log.d(TAG,
"IllegalStateException preparing MediaRecorder: "
+ e.getMessage());
releaseMediaRecorder();
return false;
} catch (IOException e) {
Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
}
System.out.println("return true in prepareVideoRecorder");
return true;
}
private static File getOutputMediaFile(int type) {
// TODO Auto-generated method stub
File mediastoredir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
System.out.println(" ### Environment.DIRECTORY_DCIM" + " " + " "
+ Environment.DIRECTORY_PICTURES);
if (!mediastoredir.exists()) {
if (!mediastoredir.mkdir()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
timestamp = new SimpleDateFormat("yyyyMMdd HHmmss", Locale.getDefault())
.format(new java.util.Date());
timestamp.split("");
System.out.println(" ### split" + timestamp);
File mediafile;
if (type == MEDIA_TYPE_VIDEO) {
mediafile = new File(mediastoredir.getPath() + File.separator
+ "VID_" + timestamp + ".mp4");
System.out.println(" Video path " + mediastoredir.getPath()
+ File.separator + "VID_" + timestamp + ".mp4");
// video path
video = mediastoredir.getPath() + File.separator + "VID_"
+ timestamp + ".mp4";
/*
* m.setsavepath(video); m.setobjecttype(play);
* c.setdatetime(timestamp); m.setdatetime(timestamp);
* //helper.adddetail(m);
*/
System.out.println(" ### IMAGE" + video);
System.out.println(" mediastoredir.getPath()"
+ mediastoredir.getPath());
System.out.println(" mediafile)" + mediafile);
System.out.println(" ### timestamp***" + timestamp);
} else {
return null;
}
return mediafile;
}
/*
* #Override protected void onActivityResult(int requestCode, int
* resultCode, Intent data) { if (requestCode ==
* CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { if (resultCode == RESULT_OK) { //
* Image captured and saved to fileUri specified in the Intent
* Toast.makeText(this, "Image saved to:\n" + data.getData(),
* Toast.LENGTH_LONG).show(); } else if (resultCode == RESULT_CANCELED) { //
* User cancelled the image capture } else { // Image capture failed, advise
* user } }
*
* if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) { if (resultCode
* == RESULT_OK) { // Video captured and saved to fileUri specified in the
* Intent Toast.makeText(this, "Video saved to:\n" + data.getData(),
* Toast.LENGTH_LONG).show(); } else if (resultCode == RESULT_CANCELED) { //
* User cancelled the video capture } else { // Video capture failed, advise
* user } } }
*/
/*
* #Override protected void onResume() { super.onResume(); if (cameraObject
* == null) { cameraObject = isCameraAvailiable();
*
* // Step 1: Unlock and set camera to MediaRecorder System.out
* .println("onResume()----Step 1: Unlock and set camera to MediaRecorder;"
* ); mMediaRecorder.setCamera(cameraObject);
* System.out.println("onResume()----isCameraAvailiable();"); }
*
* if (showCamera == null) {
* System.out.println("cameraObject = isCameraAvailiable();"); showCamera =
* new ShowCamera(this, cameraObject);
*
* preview.addView(showCamera);
*
* System.out.println("onResume()----preview.addView(showCamera);"); }
* Toast.makeText(getApplicationContext(), "onResume()",
* Toast.LENGTH_SHORT).show(); }
*/
#Override
protected void onPause() {
super.onPause();
releaseMediaRecorder(); // if you are using MediaRecorder, release it
// first
releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera() {
if (cameraObject != null) {
cameraObject.release(); // release the camera for other applications
cameraObject = null;
}
}
private void releaseMediaRecorder() {
if (mMediaRecorder != null) {
mMediaRecorder.reset(); // clear recorder configuration
mMediaRecorder.release(); // release the recorder object
mMediaRecorder = null;
cameraObject.lock(); // lock camera for later use
}
}
public class MyCameraSurfaceView extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public MyCameraSurfaceView(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int weight, int height) {
// If your preview can change or rotate, take care of those events
// here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// make any resize, rotate or reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
// The Surface has been created, now tell the camera where to draw
// the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-gene`enter code here`rated method stub
}
}
}
Here in flipcam i have change my camera view`enter code here`
I used the following code to capture image. Everything works fine, when i capture the image it has 2592x1944 size and the image is captured in landscape mode. Now i want to capture the image with the size of 534x534. I changed this parameter values params.setPictureSize(534, 534); Nothing will change. How can i do this. Thanks in advance.
DgCamActivity.java
public class DgCamActivity extends Activity implements SensorEventListener {
private Camera mCamera;
private CameraPreview mPreview;
private SensorManager sensorManager = null;
private int orientation;
private ExifInterface exif;
private int deviceHeight;
private Button ibRetake;
private Button ibUse;
private Button ibCapture;
// private FrameLayout flBtnContainer;
private File sdRoot;
private String dir;
private String fileName;
// private ImageView rotatingImage;
private int degrees = -1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
// Setting all the path for the image
sdRoot = Environment.getExternalStorageDirectory();
dir = "/SimpleCamera/";
// Getting all the needed elements from the layout
// rotatingImage = (ImageView) findViewById(R.id.imageView1);
ibRetake = (Button) findViewById(R.id.ibRetake);
ibUse = (Button) findViewById(R.id.ibUse);
ibCapture = (Button) findViewById(R.id.ibCapture);
// flBtnContainer = (FrameLayout) findViewById(R.id.flBtnContainer);
// Getting the sensor service.
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// Selecting the resolution of the Android device so we can create a
// proportional preview
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
deviceHeight = display.getHeight();
// Add a listener to the Capture button
ibCapture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
// Add a listener to the Retake button
ibRetake.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Deleting the image from the SD card/
File discardedPhoto = new File(sdRoot, dir + fileName);
discardedPhoto.delete();
// Restart the camera preview.
mCamera.startPreview();
// Reorganize the buttons on the screen
// flBtnContainer.setVisibility(LinearLayout.VISIBLE);
ibRetake.setVisibility(LinearLayout.GONE);
ibUse.setVisibility(LinearLayout.GONE);
}
});
// Add a listener to the Use button
ibUse.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Everything is saved so we can quit the app.
finish();
}
});
}
private void createCamera() {
// Create an instance of Camera
mCamera = getCameraInstance();
// Setting the right parameters in the camera
Camera.Parameters params = mCamera.getParameters();
List<Camera.Size> sizes = params.getSupportedPictureSizes();
Log.v("SUPORTED SIZE IS>>>>>.", params.getSupportedPictureSizes() + "");
Log.v("SUPORTED SIZE IS>>>>>.", sizes.size() + "");
params.setPictureSize(1600, 1200);
params.setPictureFormat(PixelFormat.JPEG);
params.setJpegQuality(100);
mCamera.setParameters(params);
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
RelativeLayout preview = (RelativeLayout) findViewById(R.id.camera_preview);
// Calculating the width of the preview so it is proportional.
float widthFloat = (float) (deviceHeight) * 4 / 3;
int width = Math.round(widthFloat);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
preview.setLayoutParams(layoutParams);
preview.addView(mPreview, 0);
}
#Override
protected void onResume() {
super.onResume();
createCamera();
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
releaseCamera();
RelativeLayout preview = (RelativeLayout) findViewById(R.id.camera_preview);
preview.removeViewAt(0);
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
public static Camera getCameraInstance() {
Camera c = null;
try {
// attempt to get a Camera instance
c = Camera.open();
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
// returns null if camera is unavailable
return c;
}
private PictureCallback mPicture = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
ibRetake.setVisibility(View.VISIBLE);
ibUse.setVisibility(View.VISIBLE);
// File name of the image that we just took.
fileName = "IMG_"
+ new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date()).toString() + ".jpg";
File mkDir = new File(sdRoot, dir);
mkDir.mkdirs();
// Main file where to save the data that we recive from the camera
File pictureFile = new File(sdRoot, dir + fileName);
try {
FileOutputStream purge = new FileOutputStream(pictureFile);
purge.write(data);
purge.close();
} catch (FileNotFoundException e) {
Log.d("DG_DEBUG", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("DG_DEBUG", "Error accessing file: " + e.getMessage());
}
try {
exif = new ExifInterface("/sdcard/" + dir + fileName);
exif.setAttribute(ExifInterface.TAG_ORIENTATION, ""
+ orientation);
exif.saveAttributes();
} catch (IOException e) {
e.printStackTrace();
}
}
};
/**
* Putting in place a listener so we can get the sensor data only when
* something changes.
*/
public void onSensorChanged(SensorEvent event) {
synchronized (this) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
RotateAnimation animation = null;
if (event.values[0] < 4 && event.values[0] > -4) {
if (event.values[1] > 0
&& orientation != ExifInterface.ORIENTATION_ROTATE_90) {
// UP
orientation = ExifInterface.ORIENTATION_ROTATE_90;
animation = getRotateAnimation(270);
degrees = 270;
} else if (event.values[1] < 0
&& orientation != ExifInterface.ORIENTATION_ROTATE_270) {
// UP SIDE DOWN
orientation = ExifInterface.ORIENTATION_ROTATE_270;
animation = getRotateAnimation(90);
degrees = 90;
}
} else if (event.values[1] < 4 && event.values[1] > -4) {
if (event.values[0] > 0
&& orientation != ExifInterface.ORIENTATION_NORMAL) {
// LEFT
orientation = ExifInterface.ORIENTATION_NORMAL;
animation = getRotateAnimation(0);
degrees = 0;
} else if (event.values[0] < 0
&& orientation != ExifInterface.ORIENTATION_ROTATE_180) {
// RIGHT
orientation = ExifInterface.ORIENTATION_ROTATE_180;
animation = getRotateAnimation(180);
degrees = 180;
}
}
if (animation != null) {
// rotatingImage.startAnimation(animation);
}
}
}
}
/**
* Calculating the degrees needed to rotate the image imposed on the button
* so it is always facing the user in the right direction
*
* #param toDegrees
* #return
*/
private RotateAnimation getRotateAnimation(float toDegrees) {
float compensation = 0;
if (Math.abs(degrees - toDegrees) > 180) {
compensation = 360;
}
// When the device is being held on the left side (default position for
// a camera) we need to add, not subtract from the toDegrees.
if (toDegrees == 0) {
compensation = -compensation;
}
// Creating the animation and the RELATIVE_TO_SELF means that he image
// will rotate on it center instead of a corner.
RotateAnimation animation = new RotateAnimation(degrees, toDegrees
- compensation, Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
// Adding the time needed to rotate the image
animation.setDuration(250);
// Set the animation to stop after reaching the desired position. With
// out this it would return to the original state.
animation.setFillAfter(true);
return animation;
}
/**
* STUFF THAT WE DON'T NEED BUT MUST BE HEAR FOR THE COMPILER TO BE HAPPY.
*/
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
CameraPreview.java
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mHolder.setSizeFromLayout();
mHolder.setFixedSize(100, 100);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the
// preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("DG_DEBUG", "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// make any resize, rotate or reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
Log.d("DG_DEBUG", "Error starting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
}
test.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:id="#+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="41dp" >
<Button
android:id="#+id/ibCapture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/relativeLayout1"
android:layout_alignLeft="#+id/camera_preview"
android:text="Capture" />
<Button
android:id="#+id/ibRetake"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="36dp"
android:layout_toRightOf="#+id/ibCapture"
android:text="ReTake" />
<Button
android:id="#+id/ibUse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="38dp"
android:text="Save" />
</RelativeLayout>
</RelativeLayout>
I believe Android will not allow for arbitrary image sizes when taking a picture, you should use the parameters.getSupportedPictureSizes() method to query the supported image sizes.
I suspect you would have to choose a big enough size to cut your desired 534x534 patch from. You could do this by using BitmapFactory methods to decode the picture that was taken and then use bitmap.getPixels() method to extract the desired patch size, or something like bitmap.createScaledBitmap() to scale your picture to the desired size.
After you have your correctly sized bitmap, you could just use bitmap.compress() to save your image, if that's the final format you are going for.