photo striped / scratched (the thumbnail view perfect) - android

My application capture and save a photo in a specific directory. The problem is when i go to the gallery to open the capture. The thumbnail view perfect, but when open the photo with HTC player the photo is striped / scratched.
I use an Activity that implements SurfaceHolder.Callback.
PictureCallback myJpeg = new PictureCallback() {
private boolean compress;
public void onPictureTaken(byte[] arg0, Camera arg1) {
File path = getPath();
File file = getName(path, imageNum);
imageNum ++;
try {
if(!path.exists())
path.mkdirs();
OutputStream imageFileOS = new FileOutputStream(file);
imageFileOS.write(arg0);
imageFileOS.close();
MediaScannerConnection.scanFile(getApplicationContext(),
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(imageNum < numDisp)
myCamera.startPreview();
else{
goToViewCapture(file);
}
}
};
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
try{
if(myPreviewRunning){
myCamera.stopPreview();
myPreviewRunning = false;
}
Camera.Parameters p = myCamera.getParameters();
p.setPreviewSize(width,height);
myCamera.setParameters(p);
myCamera.setPreviewDisplay(holder);
myCamera.startPreview();
myPreviewRunning = true;
}catch(Exception e){e.printStackTrace();}
}
public void surfaceCreated(SurfaceHolder holder) {
myCamera = Camera.open();
try {
Camera.Parameters parameters = myCamera.getParameters();
parameters.set("jpeg-quality", 70);
parameters.setPictureFormat(PixelFormat.JPEG);
myCamera.setParameters(parameters);
myCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
myCamera.release();
}
//myCamera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
myCamera.stopPreview();
myPreviewRunning = false;
myCamera.release();
myCamera = null;
}
Thanks!!!
SOLUTION:
comment this line --> //p.setPreviewSize(width,height);

Related

Android Camera and shader effects

I am working an android camera app that uses a vertex shader to apply various distortion effects to the camera preview. Although the camera preview shows the desired effect, pictures do not. How do I get the picture/image to show the same effect as the camera preview? I hope my question is clear. Many thanks in anticipation.
Code extract is as follows:
Camera Activity:
public class CameraActivity extends Activity implements SurfaceTexture.OnFrameAvailableListener{
#SuppressWarnings("deprecation")
private Camera mCamera;
private PreviewCallback mPreviewCallback;
private MyGLSurfaceView glSurfaceView;
private SurfaceTexture surface;
MyGL20Renderer renderer;
public boolean mFrameAvailable = false;
public static final int MEDIA_TYPE_IMAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.screen);
FrameLayout surface = (FrameLayout)findViewById(R.id.camera_preview);
glSurfaceView = new MyGLSurfaceView(this);
renderer = glSurfaceView.getRenderer();
// setContentView(glSurfaceView);
surface.addView(glSurfaceView);
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// get an image from the camera
// mCamera.takePicture(null, null, mPicture);
// mCamera.setOneShotPreviewCallback(mPreviewCallback);
takeSnapPhoto();
}
}
);
}
#SuppressWarnings("deprecation")
public void startCamera(int texture)
{
surface = new SurfaceTexture(texture);
surface.setOnFrameAvailableListener(this);
renderer.setSurface(surface);
mCamera = Camera.open(CameraInfo.CAMERA_FACING_BACK);
try
{
mCamera.setPreviewTexture(surface);
mCamera.startPreview();
}
catch (IOException ioe)
{
Log.w("MainActivity","CAM LAUNCH FAILED");
}
Camera.Parameters param = mCamera.getParameters();
param.setPictureSize(640, 480);
// param.setColorEffect(Camera.Parameters.EFFECT_SEPIA);
mCamera.setParameters(param);
}
public void onFrameAvailable(SurfaceTexture surfaceTexture)
{
mFrameAvailable = true;
glSurfaceView.requestRender();
}
#SuppressWarnings("deprecation")
#Override
public void onPause()
{
mFrameAvailable = false;
mCamera.stopPreview();
mCamera.release();
System.exit(0);
}
#SuppressWarnings("deprecation")
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d("CrazyMirror", "Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
// bitmap.compress(Bitmap.CompressFormat.PNG,100, fos);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("CrazyMirror", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("CrazyMirror", "Error accessing file: " + e.getMessage());
}
refreshPreview();
}
};
/** Create a File for saving an image or video */
#SuppressLint("SimpleDateFormat")
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "CrazyMirror");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("CrazyMirror", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}
else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
}
else {
return null;
}
return mediaFile;
}
#SuppressWarnings("deprecation")
public void refreshPreview() {
try {
mCamera.stopPreview();
} catch (Exception e) {}
try {
mCamera.startPreview();
} catch (Exception e) {}
}
public void takeSnapPhoto() {
mCamera.setOneShotPreviewCallback(new Camera.PreviewCallback() {
#Override
public void onPreviewFrame(byte[] data, Camera camera) {
Camera.Parameters parameters = camera.getParameters();
int format = parameters.getPreviewFormat();
//YUV formats require more conversion
if (format == ImageFormat.NV21 || format == ImageFormat.YUY2 || format == ImageFormat.NV16) {
int w = parameters.getPreviewSize().width;
int h = parameters.getPreviewSize().height;
// Get the YuV image
YuvImage yuv_image = new YuvImage(data, format, w, h, null);
// Convert YuV to Jpeg
Rect rect = new Rect(0, 0, w, h);
ByteArrayOutputStream output_stream = new ByteArrayOutputStream();
yuv_image.compressToJpeg(rect, 100, output_stream);
byte[] byt = output_stream.toByteArray();
FileOutputStream outStream = null;
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "CrazyMirror");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
try {
// Write to SD Card
// File file = createFileInSDCard(FOLDER_PATH, "Image_"+System.currentTimeMillis()+".jpg");
//Uri uriSavedImage = Uri.fromFile(file);
outStream = new FileOutputStream(mediaFile);
outStream.write(byt);
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
});}
}

How to make camera photo correct on every device / Android version?

I wrote this camera app, but I cannot got correct image on every device
I found that there are two types camera on different devices, so I cannot rotate photo correctly on every device.
I have looked into some open source camera app, but don't see any logic to handle this problem, and these apps still rotate correctly.
How to detect the type of camera? so that I can rotate photo to correct degree.
public class Camera01 extends Activity implements SurfaceHolder.Callback {
SurfaceHolder surfaceHolder;
SurfaceView surfaceView1;
Button button1;
Camera camera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera01);
button1=(Button)findViewById(R.id.button1);
surfaceView1=(SurfaceView)findViewById(R.id.surfaceView1);
surfaceHolder=surfaceView1.getHolder();
surfaceHolder.addCallback(this);
button1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
camera.autoFocus(afcb);
}
});
}
PictureCallback jpeg =new PictureCallback(){
public void onPictureTaken(byte[] data, Camera camera) {
new SaveImageTask().execute(data);
camera.startPreview();
}
};
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
public void surfaceCreated(SurfaceHolder holder) {
camera=Camera.open(1);
try {
Camera.Parameters params = camera.getParameters();
List<Camera.Size> sizes = params.getSupportedPictureSizes();
params.setPictureFormat(PixelFormat.JPEG);
Camera.Size mSize = sizes.get(0);
params.setPictureSize(mSize.width, mSize.height);
params.setRotation(90); // <<<<<<<<<<<<<<<<<<<<< to correct photo direction
camera.setParameters(params);
camera.setPreviewDisplay(surfaceHolder);
// camera.setDisplayOrientation(90);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
}
AutoFocusCallback afcb= new AutoFocusCallback(){
public void onAutoFocus(boolean success, Camera camera) {
if(success){
camera.takePicture(null, null, jpeg);
}
}
};
private class SaveImageTask extends AsyncTask<byte[], Void, Void> {
#Override
protected Void doInBackground(byte[]... data) {
FileOutputStream outStream = null;
try {
File dir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "test");
if (! dir.exists()){
if (! dir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
outStream.write(data[0]);
outStream.flush();
outStream.close();
Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(outFile));
sendBroadcast(mediaScanIntent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return null;
}
}
}
You can make correct rotation if you have filepath of image with scaled bitmap of image then use below method:
public Bitmap checkRotation(String filePath, Bitmap scaledBitmap) {
ExifInterface exif;
try {
exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 0);
Log.d("EXIF", "Exif: " + orientation);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 3) {
matrix.postRotate(180);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 8) {
matrix.postRotate(270);
Log.d("EXIF", "Exif: " + orientation);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
true);
} catch (IOException e) {
e.printStackTrace();
}
return scaledBitmap;
}

How to send multiple images to another activity in android?

In my application i have created a custom camera where it captures images and save it in sd card. And also can view it in second activity. But it just replaces the previous images which i dont want. How to send multiple images to second activity?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.surfaceview);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.custom, null);
LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
click = (Button) findViewById(R.id.button_capture);
click.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
}});
}
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
Bitmap bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
filepath = Environment.getExternalStorageDirectory()+"/testing/"+"test.3gp";
System.out.println("thumbnail path~~~~~~"+filepath);
File file = new File(filepath);
Uri uriTarget = Uri.fromFile(file);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(CustomCameraActivity.this, "Image saved: " + uriTarget.toString(), Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("result",filepath.toString());
setResult(1,returnIntent);
finish();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// camera.startPreview();
}};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
Just Convert your image into bitmap and pass that Bitmap in another activity by yourIntent.putExra("key",bitmap);
Or Use this:
private File imageFile;
private Uri imageUri;
private static final int CAMERA_REQUEST_CODE = 100;
private String imagePath
private Uri getTempUri() {
// Create an image file name
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String dt = sdf.format(new Date());
imageFile = null;
imageFile = new File(Environment.getExternalStorageDirectory()
+ "/foldername/", "Camera_" + dt + ".jpg");
Applog.Log(
TAG,
"New Camera Image Path:- "
+ Environment.getExternalStorageDirectory()
+ "/foldername/" + "Camera_" + dt + ".jpg");
File file = new File(Environment.getExternalStorageDirectory()
+ "/foldername");
if (!file.exists()) {
file.mkdir();
}
if (!imageFile.exists()) {
try {
imageFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
imagePath = Environment.getExternalStorageDirectory() + "/foldername/"
+ "Camera_" + dt + ".jpg";
imageUri = Uri.fromFile(imageFile);
return imageUri;
}
Now When you start activty for camera.
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(
MediaStore.EXTRA_OUTPUT,
getTempUri());
startActivityForResult(cameraIntent,
CAMERA_REQUEST_CODE);
Now In ActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (CAMERA_REQUEST_CODE == requestCode && resultCode == RESULT_OK) {
String yourUri=ImagePath;
//now store this Uri it will contain capture image url.
}
}

Captured image gets distorted when saved - Android Surfaceholder HTC Desire S

I'm using the Surfaceholder and the camera to capture an image but when I do it on my HTC Desire S the captured image looks like this. This is not what it looks like in the preview-view.
It works on two of the other phones I have been testing on so it should be a device dependant issue but I can't figure out what.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_camera_overlay);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.overlay, null);
LayoutParams layoutParamsControl
= new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
Button buttonTakePicture = (Button)findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
}});
}
...
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] byteArray, Camera arg1) {
//Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String date = dateFormat.format(new Date());
String _path = Environment.getExternalStorageDirectory() + File.separator + "xxx" + File.separator + "Livboj" + date + ".jpg";
File file = new File( _path );
Uri uriTarget = Uri.fromFile( file );
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(byteArray);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(CameraOverlayActivity.this,"Image saved: " + uriTarget.toString(),Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
camera.startPreview();
}};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
Parameters parameters = camera.getParameters();
Camera.Size size = getBestPreviewSize(width, height);
parameters.setPreviewSize(size.width, size.height);
Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
if(display.getRotation() == Surface.ROTATION_0)
{
camera.setDisplayOrientation(90);
}
if(display.getRotation() == Surface.ROTATION_90)
{
}
if(display.getRotation() == Surface.ROTATION_180)
{
}
if(display.getRotation() == Surface.ROTATION_270)
{
camera.setDisplayOrientation(180);
}
camera.setParameters(parameters);
previewCamera();
}
private Camera.Size getBestPreviewSize(int width, int height)
{
Camera.Size result=null;
Camera.Parameters p = camera.getParameters();
for (Camera.Size size : p.getSupportedPreviewSizes()) {
if (size.width<=width && size.height<=height) {
if (result==null) {
result=size;
} else {
int resultArea=result.width*result.height;
int newArea=size.width*size.height;
if (newArea>resultArea) {
result=size;
}
}
}
}
return result;
}
public void previewCamera()
{
try
{
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
}
catch(Exception e)
{
Log.d("Camera", "Cannot start preview", e);
}
}
I don't know it the problem is in the saving or in the capturing. Has anyone encountered the same problem? Thanks in advance!

how can i detect the front camera and use to capture an image?

I have my codes here that captured an image automatically using back camera and saved it to the gallery, my problem is, I want the front camera to use to capture an image. How can i detect the front camera? I really need help for this.
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
iv_image = (ImageView) findViewById(R.id.imageView);
sv = (SurfaceView) findViewById(R.id.surfaceView);
sHolder = sv.getHolder();
sHolder.addCallback(this);
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
{
parameters = mCamera.getParameters();
mCamera.setParameters(parameters);
//mCamera.startPreview();
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
#Override
public void onPictureTaken(byte[] data, Camera camera)
{
Uri uriTarget = getContentResolver().insert
(Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(TakePictureActivity.this,
"Image saved: " + uriTarget.toString(), Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
iv_image.setImageBitmap(bmp);
}
};
mCamera.takePicture(null, null, mCall);
}
#Override
public void surfaceCreated(SurfaceHolder holder)
{
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
If you are using API level 9 (Android 2.3) or above, you can do the following to calculate the index of the (first) front-facing camera:
int getFrontCameraId() {
CameraInfo ci = new CameraInfo();
for (int i = 0 ; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, ci);
if (ci.facing == CameraInfo.CAMERA_FACING_FRONT) return i;
}
return -1; // No front-facing camera found
}
you can then use the index for the Camera.open method, e.g.:
int index = getFrontCameraId();
if (index == -1) error();
Camera c = Camera.open(index);
To get the relevant camera.
Credits

Categories

Resources