How to add front-camera to SurfaceView and take pictures with it? - java

Hi
How can I add front-camera view to SurfaceView like I did with the "REAL CAMERA". Here's my code:
CameraActivity.java
**public class CameraActivity extends Activity implements SurfaceHolder.Callback{
Camera camera;
#InjectView(R.id.s)
SurfaceView surfaceView;
#InjectView(R.id.takeaphoto)
ImageView imageView;
SurfaceHolder surfaceHolder;
Camera.PictureCallback callback;
private int cameraId = 0;
Camera.ShutterCallback shutterCallback;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.camera_activity);
ButterKnife.inject(this);
surfaceHolder=surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cameraImage();
}
});
callback = new android.hardware.Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes, android.hardware.Camera camera) {
FileOutputStream outputStream=null;
File file_image = getDirc();
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyymmddhhmms");
String date = simpleDateFormat.format(new Date());
String photo_file="PI_"+date+".jpg";
String file_name = file_image.getAbsolutePath()+"/"+photo_file;
File picfile=new File(file_name);
try {
outputStream=new FileOutputStream(picfile);
outputStream.write(bytes);
outputStream.close();
}catch (FileNotFoundException e){}
catch (IOException ex){}
finally {
}
refreshCamera();
refreshGallery(picfile);
try {
camera.stopPreview();
}catch (Exception e){}
try{
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}catch (Exception e){}
}
};
}
private void refreshGallery(File file){
Intent intent=new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
}
public void refreshCamera(){
if (surfaceHolder.getSurface() == null){
return;
}
}
private File getDirc(){
File dics = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
return new File(dics ,"Camera");
}
public void cameraImage(){
camera.takePicture(null , null ,callback);
MediaPlayer mediaPlayer = MediaPlayer.create(this , R.raw.sound);
mediaPlayer.start();
}
public void surfaceCreated(SurfaceHolder surfaceHolder ) {
try {
camera = Camera.open(0);
}catch (RuntimeException ex){}
Camera.Parameters parameters;
parameters = camera.getParameters();
parameters.setPreviewFrameRate(60);
parameters.setPreviewSize(1920 , 1080);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
camera.setParameters(parameters);
camera.setDisplayOrientation(90);
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}catch (Exception e){
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
refreshCamera();
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
camera.stopPreview();
camera.release();
camera=null;
}
public void frontCamera(View view) {
if (cameraId == 0){
try {
camera = Camera.open(1);
}catch (RuntimeException ex){}
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}catch (Exception e){
}
}
else{
try {
camera = Camera.open(0);
}catch (RuntimeException ex){}
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}catch (Exception e){
}
}
}
}**
And the XML if it's even needed for this:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rel">
<SurfaceView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/s">
</SurfaceView>
<RelativeLayout
android:layout_width="match_parent"
android:id="#+id/rel2"
android:background="#color/colorPrimaryDark"
android:layout_alignParentBottom="true"
android:layout_height="150dp">
<ImageView
android:id="#+id/takeaphoto"
android:background="#drawable/button_press"
android:layout_height="80dp"
android:layout_width="80dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/rel1"
android:background="#color/colorPrimaryDark"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<ImageView
android:layout_width="30dp"
android:layout_marginEnd="10dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:src="#drawable/switchcamera"
android:id="#+id/imageView" />
</RelativeLayout>
</RelativeLayout>
</FrameLayout>
UPDATE: Now updated my code this way, but still showing error,
An error occurred while connecting to camera: 1

Modify this line
camera = android.hardware.Camera.open();
to
camera = android.hardware.Camera.open(1);
Note: use id 0 for back cam and 1 for front cam. Usually this is same for all fones. So i dont think finding out the id everytime is unnecc overhead.

Use this method to get the id of the front facing camera and pass it as a parameter to camera.open(int id)
I presume you want to toggle the cameras on the click of a button by calling the method frontCamera(View view) which I changed to switchCamera(View view) and edited you code as shown below:
public class CameraActivity extends Activity implements SurfaceHolder.Callback{
Camera camera;
#InjectView(R.id.s)
SurfaceView surfaceView;
#InjectView(R.id.takeaphoto)
ImageView imageView;
SurfaceHolder surfaceHolder;
Camera.PictureCallback callback;
private int cameraId = 0;
Camera.ShutterCallback shutterCallback;
private boolean frontCamera;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.camera_activity);
ButterKnife.inject(this);
surfaceHolder=surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cameraImage();
}
});
callback = new android.hardware.Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes, android.hardware.Camera camera) {
FileOutputStream outputStream=null;
File file_image = getDirc();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmddhhmms");
String date = simpleDateFormat.format(new Date());
String photo_file="PI_"+date+".jpg";
String file_name = file_image.getAbsolutePath()+"/"+photo_file;
File picfile=new File(file_name);
try {
outputStream=new FileOutputStream(picfile);
outputStream.write(bytes);
outputStream.close();
}catch (FileNotFoundException e){}
catch (IOException ex){}
finally {
}
refreshCamera();
refreshGallery(picfile);
try {
camera.stopPreview();
}catch (Exception e){}
try{
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}catch (Exception e){}
}
};
}
private void refreshGallery(File file){
Intent intent=new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
}
public void refreshCamera(){
if (surfaceHolder.getSurface() == null){
return;
}
}
private File getDirc(){
File dics = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
return new File(dics ,"Camera");
}
public void cameraImage(){
camera.takePicture(null , null ,callback);
MediaPlayer mediaPlayer = MediaPlayer.create(this , R.raw.sound);
mediaPlayer.start();
}
public void surfaceCreated(SurfaceHolder surfaceHolder ) {
try {
camera = Camera.open(0);
}catch (RuntimeException ex){}
Camera.Parameters parameters;
parameters = camera.getParameters();
parameters.setPreviewFrameRate(60);
parameters.setPreviewSize(1920 , 1080);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
camera.setParameters(parameters);
camera.setDisplayOrientation(90);
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}catch (Exception e){
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
refreshCamera();
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
camera.stopPreview();
camera.release();
camera=null;
}
public void switchCamera(View view) {
if (frontCamera){
try {
camera = Camera.open(defaultBackCamera());
}catch (RuntimeException ex){}
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}catch (Exception e){
}
}
else{
try {
camera = Camera.open(getFrontCameraId());
}catch (RuntimeException ex){}
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}catch (Exception e){
}
}
}
private int getFrontCameraId() {
int availableCameras = Camera.getNumberOfCameras();
Camera.CameraInfo info = new Camera.CameraInfo();
for (int i = 0; i < availableCameras; i++) {
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
frontCamera = true;
return i;
}
}
return -1;
}
private int defaultBackCamera() {
int numberOfCameras = Camera.getNumberOfCameras();
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
frontCamera = false;
return i;
}
}
return -1;
}
}
Good luck1

Related

Custom Camera not saving the whole image

I have built an android custom camera in this way:
//CameraActivity.java
public class CameraActivity extends AppCompatActivity implements CameraPreview.OnCameraStatusListener {
String path, TAG = "CameraActivity";
private CameraPreview cameraPreview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_camera);
Button takePhoto = findViewById(R.id.takePhoto);
takePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "===takePhoto()===");
if (cameraPreview != null) {
cameraPreview.takePicture();
}
}
});
//Start camera
initCameraPreview();
}
private void initCameraPreview() {
Log.e(TAG, "===initCameraPreview()===");
cameraPreview = findViewById(R.id.cameraPreview);
cameraPreview.setOnCameraStatusListener(this);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onCameraStopped(byte[] data) throws JSONException {
Log.e("TAG", "===onCameraStopped===");
File mSaveFile = getOutputMediaFile();
saveToFile(data, mSaveFile);
}
public File getOutputMediaFile() {
File mediaStorageDir =
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CustomCameraPics");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.e(TAG, "failed to create directory");
return null;
}
}
long time = System.currentTimeMillis();
File file = new File(mediaStorageDir.getPath() + File.separator + "myPic_" + time + ".png");
path = file.getPath();
Log.e("imagePath", path);
return file;
}
#RequiresApi(api = Build.VERSION_CODES.N)
public void saveToFile(byte[] bytes, File file) throws JSONException {
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
Log.e("Image", "Saved");
Toast.makeText(CameraActivity.this, "Image Saved", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//activity_camera.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.sukshi.mycamera.CameraActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.shank.mycamera.CameraPreview
android:id="#+id/cameraPreview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Take pic"
android:id="#+id/takePhoto"/>
</RelativeLayout>
</RelativeLayout>
//CameraPreview.java
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "CameraPreview";
private OnCameraStatusListener listener;
private Camera camera;
private SurfaceHolder holder;
private Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
camera.stopPreview();
} catch (Exception e) {
}
if (null != listener) {
try {
listener.onCameraStopped(data);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
};
public void takePicture() {
Log.e(TAG, "===takePicture()===");
if (camera != null) {
try {
camera.takePicture(null, null, pictureCallback);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public CameraPreview(Context context, AttributeSet attrs) {
super(context, attrs);
holder = getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public interface OnCameraStatusListener {
void onCameraStopped(byte[] data) throws JSONException;
}
public void setOnCameraStatusListener(OnCameraStatusListener listener) {
this.listener = listener;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.e(TAG, "==surfaceCreated==");
camera = getCameraInstance();
try {
camera.setPreviewDisplay(holder);
} catch (Exception e) {
Log.e(TAG, "Error setting camera preview", e);
camera.release();
camera = null;
}
//update()
if (camera != null) {
camera.startPreview();
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, cameraInfo);
}
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.e(TAG, "==surfaceChanged==");
try {
camera.stopPreview();
} catch (Exception e) {
}
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (Exception e) {
Log.e(TAG, "Error starting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.e(TAG, "==surfaceDestroyed==");
camera.release();
camera = null;
}
public static Camera getCameraInstance() {
Camera camera = null;
int cameraId = 0;
boolean frontCameraFound = false;
try {
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
frontCameraFound = true;
}
}
if (frontCameraFound) {
camera = Camera.open(cameraId);
} else {
camera = Camera.open();
}
Camera.Parameters parameters = camera.getParameters();
camera.setDisplayOrientation(90);
parameters.setRotation(270);
camera.setParameters(parameters);
} catch (Exception e) {
Log.e(TAG, "getCamera failed");
}
return camera;
}
}
It saves the image when you click 'TAKE PIC' button.
My requirement: the whole image that the user can see on the screen in preview should be saved.
The problem I'm facing is that in some of the phones the image/bitmap saved doesn't contain everything that is shown to the user on screen.
As #CommonsWare has explained, there is no requirement that a captured picture should be same as preview picture. You can skip camera.takePicture() altogether, and in your cameraPreview.takePicture(), save the latest preview frame as bitmap.
The advantages of this approach are that your are guaranteed that the same image as the user sees in the preview is saved, and it happens with no delay.
The drawback is that the resolution and quality for image returned from camera.takePicture() may be noticeably better.
If you not satisfied with preview frame quality, you can use the same size for setPreviewSize() and for setPictureSize(), if the size is supported for both getSupportedPreviewSizes() and getSupportedPictureSizes(): usually you can find a satisfactory pair.
If you are not satisfied with the preview frame resolution, at least choose the same aspect ratio for setPreviewSize() and for setPictureSize(). Some devices produce really weird results when the two don't match.
But note that these steps can not guarantee that the captured image will be the same as previewed, even only because takePicture() inevitably happens with some delay.
One more remark: if you target Android N and above, consider switching from the deprecated Camera API to the camera2 API.

Android Camera: Attempt to invoke virtual method Android Camera Parameters on android.hardware.Camera.getParameters()' on a null object reference

I used my Fabric-service and found this error on most of the devices that are running my app.
Error was this:
Fatal Exception: java.lang.NullPointerException Attempt to invoke
virtual method 'android.hardware.Camera$Parameters
android.hardware.Camera.getParameters()' on a null object reference
Here's my code:
public class CameraActivity extends Activity implements SurfaceHolder.Callback{
android.hardware.Camera camera;
int moi = 0;
#InjectView(R.id.s)
SurfaceView surfaceView;
#InjectView(R.id.takeaphoto)
ImageView imageView;
SurfaceHolder surfaceHolder;
private Camera.Face[] mFaces;
// Draw rectangles and other fancy stuff:
private FaceOverlayView mFaceView;
private int mOrientation;
private float x1,x2;
static final int MIN_DISTANCE = 150;
private int mOrientationCompensation;
private OrientationEventListener mOrientationEventListener;
// Let's keep track of the display rotation and orientation also:
private int mDisplayRotation;
private int mDisplayOrientation;
Camera.PictureCallback callback;
int cameraId = 0;
Camera.ShutterCallback shutterCallback;
private Camera.FaceDetectionListener faceDetectionListener = new Camera.FaceDetectionListener() {
#Override
public void onFaceDetection(Camera.Face[] faces, Camera camera) {
Log.d("onFaceDetection", "Number of Faces:" + faces.length);
// Update the view now!
mFaceView.setFaces(faces);
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
Fabric.with(this, new Crashlytics());
Fabric.with(this, new Answers());
setContentView(R.layout.camera_activity);
mFaceView = new FaceOverlayView(this);
addContentView(mFaceView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// Create and Start the OrientationListener:
mOrientationEventListener = new SimpleOrientationEventListener(this);
mOrientationEventListener.enable();
SharedPreferences pap = this.getSharedPreferences(
"AD1", Context.MODE_PRIVATE);
boolean frr = pap.getBoolean("fr", false);
if (!frr) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Tip");
builder.setMessage("Use the beautiful filters by swiping from right to left")
.setCancelable(true)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences e = getApplicationContext().getSharedPreferences(
"AD1", Context.MODE_PRIVATE);
SharedPreferences.Editor d = e.edit();
d.putBoolean("fr", true);
d.commit();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
}
ButterKnife.inject(this);
surfaceHolder=surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cameraImage();
}
});
callback = new android.hardware.Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes, android.hardware.Camera camera) {
FileOutputStream outputStream=null;
File file_image = getDirc();
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyymmddhhmms");
String date = simpleDateFormat.format(new Date());
String photo_file="PI_"+date+".jpg";
String file_name = file_image.getAbsolutePath()+"/"+photo_file;
File picfile=new File(file_name);
try {
outputStream=new FileOutputStream(picfile);
outputStream.write(bytes);
outputStream.close();
}catch (FileNotFoundException e){}
catch (IOException ex){}
finally {
}
refreshCamera();
refreshGallery(picfile);
try {
camera.stopPreview();
}catch (Exception e){}
try{
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}catch (Exception e){}
}
};
}
private void refreshGallery(File file){
Intent intent=new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
}
public void refreshCamera(){
if (surfaceHolder.getSurface() == null){
return;
}
}
private class SimpleOrientationEventListener extends OrientationEventListener {
public SimpleOrientationEventListener(Context context) {
super(context, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onOrientationChanged(int i) {
// We keep the last known orientation. So if the user first orient
// the camera then point the camera to floor or sky, we still have
// the correct orientation.
if (orientation == ORIENTATION_UNKNOWN) return;
mOrientation = Util.roundOrientation(orientation, mOrientation);
// When the screen is unlocked, display rotation may change. Always
// calculate the up-to-date orientationCompensation.
int orientationCompensation = mOrientation
+ Util.getDisplayRotation(CameraActivity.this);
if (mOrientationCompensation != orientationCompensation) {
mOrientationCompensation = orientationCompensation;
mFaceView.setOrientation(mOrientationCompensation);
}
}
}
private File getDirc(){
File dics = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
return new File(dics ,"Camera");
}
public void cameraImage(){
camera.takePicture(null , null ,callback);
MediaPlayer mediaPlayer = MediaPlayer.create(this , R.raw.sound);
mediaPlayer.start();
}
public void surfaceCreated(SurfaceHolder surfaceHolder ) {
try {
camera = android.hardware.Camera.open();
}catch (RuntimeException ex){}
android.hardware.Camera.Parameters parameters;
parameters = camera.getParameters();
camera.setFaceDetectionListener(faceDetectionListener);
camera.startFaceDetection();
parameters.setPreviewFrameRate(20);
List<Camera.Size> customSizes = parameters.getSupportedPreviewSizes();
Camera.Size customSize = customSizes.get(0); //Added size
parameters.setPreviewSize(customSize.width, customSize.height);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
camera.setParameters(parameters);
camera.setDisplayOrientation(90);
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}catch (Exception e){
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
refreshCamera();
setDisplayOrientation();
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
camera.stopPreview();
camera.release();
camera=null;
}
public void frontCamera(View view) {
camera.stopPreview();
camera.release();
camera=null;
if (cameraId == 0){
try {
camera = android.hardware.Camera.open(1);
}catch (RuntimeException ex){}
android.hardware.Camera.Parameters parameters;
camera.setFaceDetectionListener(faceDetectionListener);
camera.startFaceDetection();
parameters = camera.getParameters();
parameters.setPreviewFrameRate(20);
List<Camera.Size> customSizes = parameters.getSupportedPreviewSizes();
Camera.Size customSize = customSizes.get(0); //Added size
parameters.setPreviewSize(customSize.width, customSize.height);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
camera.setParameters(parameters);
camera.setDisplayOrientation(90);
cameraId = 1;
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}catch (Exception e){
}
}
else{
try {
camera = android.hardware.Camera.open();
}catch (RuntimeException ex){}
android.hardware.Camera.Parameters parameters;
camera.setFaceDetectionListener(faceDetectionListener);
camera.startFaceDetection();
parameters = camera.getParameters();
parameters.setPreviewFrameRate(20);
List<Camera.Size> customSizes = parameters.getSupportedPreviewSizes();
Camera.Size customSize = customSizes.get(0); //Added size
parameters.setPreviewSize(customSize.width, customSize.height);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
camera.setParameters(parameters);
camera.setDisplayOrientation(90);
cameraId = 0;
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}catch (Exception e){
}
}
}
private void setDisplayOrientation() {
// Now set the display orientation:
mDisplayRotation = Util.getDisplayRotation(CameraActivity.this);
mDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, 0);
camera.setDisplayOrientation(mDisplayOrientation);
if (mFaceView != null) {
mFaceView.setDisplayOrientation(mDisplayOrientation);
}
}
Here's my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.camera">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/pc"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashScreen"
android:theme="#style/AppTheme"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".CameraActivity"
android:screenOrientation="portrait"
>
</activity>
<meta-data
android:name="io.fabric.ApiKey"
android:value="e7ded6b46068e619fd1d96f6b9eeaac888fe83f5" />
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
Check the app in your device Settings, if the required permissions are given or not. In my case, this was the reason for Exception, that I had not given permissions from the Settings.
Hope it helps you.
Here is your problem. Your camera object is instantiated only if there is no RuntimeException. So, if this exception happens, camera == null;.
try {
camera = android.hardware.Camera.open();
}catch (RuntimeException ex){}
// Here is your problem. Catching RuntimeException will make camera object null,
// so method 'getParameters();' won't work :)
android.hardware.Camera.Parameters parameters;
parameters = camera.getParameters();
camera.setFaceDetectionListener(faceDetectionListener);
camera.startFaceDetection();
parameters.setPreviewFrameRate(20);
List<Camera.Size> customSizes = parameters.getSupportedPreviewSizes();
Camera.Size customSize = customSizes.get(0); //Added size
parameters.setPreviewSize(customSize.width, customSize.height);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
camera.setParameters(parameters);
camera.setDisplayOrientation(90);
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}catch (Exception e){
}
}
try {
camera = android.hardware.Camera.open();
}catch (RuntimeException ex){}
if(camera != null){
android.hardware.Camera.Parameters parameters;
parameters = camera.getParameters();
camera.setFaceDetectionListener(faceDetectionListener);
camera.startFaceDetection();
parameters.setPreviewFrameRate(20);
List<Camera.Size> customSizes = parameters.getSupportedPreviewSizes();
Camera.Size customSize = customSizes.get(0); //Added size
parameters.setPreviewSize(customSize.width, customSize.height);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
camera.setParameters(parameters);
camera.setDisplayOrientation(90);
}
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}catch (Exception e){
}
}
After initializing the camera you can put a simple if condition where you can check if(camera != null){ // the code for parameter}

How to turn on flashlight and front camera at the same time in android

In one of the requirement in my app I need to pop up an activity containing the front camera preview,at this same time I need to turn on the flashlight as well.However I observe that,I am able to turn on the flashlight and back camera but not front camera and flashlight together.Following is my code:
public class Cam extends Activity {
private static int cameraId = 0;
private Camera camera;
//Adding for camera preview
public static FrameLayout preview;
public static CameraPreview mPreview;
Context context;
ImageButton btnSwitch;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Cam","Inside onCreate");
setContentView(R.layout.cam);
context = getApplicationContext();
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
startCamera();
// displaying button image
toggleButtonImage();
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
turnOffFlash();
} else {
turnOnFlash();
}
}
});
}
#Override
protected void onPause() {
super.onPause();
turnOffFlash();
Log.e("Cam","Inside onPause");
try {
if (camera != null) {
camera.release();
camera = null;
preview.removeView(mPreview);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
Log.e("Cam","Inside onResume");
try {
if(camera ==null) {
Log.d("Cam","in resume,camera is null");
try {
camera = android.hardware.Camera.open(cameraId); //opens front cam
// camera = Camera.open(); when I use this I can on/off the flashlight,since I am using the back camera.
mPreview = new CameraPreview(this, camera);
preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.e("Cam","Inside onDestroy");
if (camera != null) {
try {
camera.release();
camera = null;
preview.removeView(mPreview);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void startCamera() {
Log.e("Cam","Inside doInBackground");
String msg = "";
// Do we have a camera?
try {
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
} else {
cameraId = AppFunctions.findFrontFacingCamera();//A function that returns 0 for front camera
if (cameraId < 0) {
} else {
try {
camera = Camera.open(cameraId);//opens front cam
// camera = Camera.open(); when I use this I can on/off the flashlight,since I am calling the back camera.
params = camera.getParameters();
Log.e("Cam","camera id" + cameraId);
Log.e("Cam","params" + params);
} catch (Exception e) {
e.printStackTrace();
}
try {
mPreview = new CameraPreview(getApplicationContext(), camera);
preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e3) {
e3.printStackTrace();
}
}
private void turnOnFlash() {
Log.v("Cam","Inside turnOnFlash");
if (!isFlashOn) {
if (camera == null || params == null) {
Log.v("Cam","camera or param is null");
return;
}
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
/*
* Turning Off flash
*/
private void turnOffFlash() {
Log.v("Cam","Inside turnOffFlash");
if (isFlashOn) {
if (camera == null || params == null) {
Log.v("Cam","camera or param is null");
return;
}
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
private void toggleButtonImage(){
if(isFlashOn){
btnSwitch.setImageResource(R.drawable.btn_switch_on);
}else{
btnSwitch.setImageResource(R.drawable.btn_switch_off);
}
}
}
Manifest
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.front" />
<permission android:name="android.permission.FLASHLIGHT" />
How can I turn on the flashlight and front cam simultaneously? Any help would be appreciated !
Try to turn on the flashlight in background then open your front camera.
actually you can turn front camera and flashlight in background.
Here how to open flashlight in background: this
Here how to turn on camera in background: this
Flashlight
public void onToggleClicked(View view) {
PackageManager pm = context.getPackageManager();
final Parameters p = camera.getParameters();
if (isFlashSupported(pm)) {
boolean on = ((ToggleButton) view).isChecked();
if (on) {
Log.i("info", "torch is turn on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
} else {
Log.i("info", "torch is turn off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
}
Camera :
ImageButton ib = (ImageButton) findViewById(R.id.buttonToast);
ib.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAPTURE_IMAGE_CAPTURE_CODE);
}
});
The following code checks for the availability of a front camera:
private Camera openFrontFacingCameraGingerbread() {
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
cam = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return cam;
}
Then add the following permissions in the AndroidManifest.xml file:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />
Note: This feature is available in Gingerbread(2.3) and Up Android Version.
I recommend using surfaceView like in this example to implement a working flashlight.
Hope this helps :)

Android: How do i set imageview with photo taken through a custom camera

I have a custom camera application whereby when i press the capture button, the image captured will appear on the next activity as a preview image.
This is far as i went -
MainActivity.java
public class MainActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
private File pictureFile;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
final ImageView view = (ImageView) findViewById(R.id.imageView1);
preview.addView(mCameraPreview);
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
}
/**
* Helper method to access the camera returns null if it cannot get the
* camera or does not exist
*
* #return
*/
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
my CameraPreview.java
public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
// Constructor that obtains context and camera
#SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
}
My activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/container"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/Frame"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_weight="1" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:src="#drawable/ic_launcher" />
</FrameLayout>
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
<Button
android:id="#+id/button_capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Capture" />
So far, i've tried to set the background resource of my one of my Imageview, view, using mPicture or even converting pictureFile but to no avail. However the preview image appear on the camerapreview.
any experienced programmers out there who know how to deal with this? thanks!
I added just few lines to your onPictureTaken() callback:
public void onPictureTaken(byte[] data, Camera camera) {
pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
// ---- added to display imageView ----
BitmapFactory.Options scalingOptions = new BitmapFactory.Options();
scalingOptions.inSampleSize = camera.getParameters().getPictureSize().width / imageView.getMeasuredWidth();
final Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length, scalingOptions);
imageView.setImageBitmap(bmp);
imageView.setVisibility(ImageView.VISIBLE);
// ---- end of changes to display imageView ----
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}

How can i capture image with a touch on surface view

public class AndroidCamera extends Activity implements OnTouchListener, SurfaceHolder.Callback{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;;
PictureCallback rawCallback;
ShutterCallback shutterCallback;
PictureCallback jpegCallback;
EditText txtData, Info,Age;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStartCameraPreview = (Button)findViewById(R.id.startcamerapreview);
Button buttonStopCameraPreview = (Button)findViewById(R.id.stopcamerapreview);
Button buttonCapturePreview = (Button) findViewById(R.id.capturepreview);
txtData = (EditText) findViewById(R.id.editText1);
Info = (EditText) findViewById(R.id.Name);
Info.setHint("enter name");
Age = (EditText) findViewById(R.id.Age);
Age.setHint("Age");
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
rawCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
Log.d("Log", "onPictureTaken - raw");
}
};
shutterCallback = new ShutterCallback()
{
public void onShutter() {
Log.i("Log", "onShutter'd");
}
};
// onTouchEvent(null);
jpegCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Asw");
imagesFolder.mkdirs();
Date d = new Date();
CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
File output = new File(imagesFolder, s.toString() + ".jpg");
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{}
Log.d("Log", "onPictureTaken - jpeg");
}
};
buttonStartCameraPreview.setOnClickListener(new Button.OnClickListener()
{
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onClick(View v)
{
if(!previewing)
{
camera = Camera.open(0);
if (camera != null)
{
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
}
catch (IOException e)
{
e.printStackTrace();
}
}else txtData.setText("null");
}
}});
buttonCapturePreview.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
captureImage();
}
private void captureImage()
{
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
buttonStopCameraPreview.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v)
{
if(camera != null && previewing)
{
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}});
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.android_camera, menu);
return true;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height)
{
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
// TODO Auto-generated method stub
}
public boolean onTouch(View v, MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_MOVE)
{
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
return super.onTouchEvent(event);
//return false;
}
I have used a button to capture the image. Now i wanted to capture and save the image with just a touch on surface view. I wrote some code.Its not showing any error but it is not working also. Could you please tell me where i am going wrong. Please help
Try this to take screen shot programmatically...
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + ACCUWX.IMAGE_APPEND;
// create bitmap screen capture
Bitmap bitmap;
View v1 = mCurrentUrlMask.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
OutputStream fout = null;
imageFile = new File(mPath);
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class SnapShot extends Activity implements OnClickListener,
SurfaceHolder.Callback, Camera.PictureCallback {
SurfaceView cameraView;
SurfaceHolder surfaceHolder;
Camera camera;
LayoutInflater inflater;
Uri imageFileUri;
Button save;
Button retry;
View viewControl;
LayoutParams layoutParamsControl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_camera);
cameraView = (SurfaceView) this.findViewById(R.id.CameraView);
surfaceHolder = cameraView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceHolder.addCallback(this);
cameraView.setFocusable(true);
cameraView.setFocusableInTouchMode(true);
cameraView.setClickable(true);
cameraView.setOnClickListener(this);
inflater = LayoutInflater.from(getBaseContext());
viewControl = inflater.inflate(R.layout.camera_control, null);
save = (Button) viewControl.findViewById(R.id.vc_btn_keep);
retry = (Button)viewControl.findViewById(R.id.vc_btn_discard);
layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
camera.startPreview();
}
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
try {
Camera.Parameters parameters = camera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
// This is an undocumented although widely known feature
parameters.set("orientation", "portrait");
// For Android 2.2 and above
camera.setDisplayOrientation(90);
// Uncomment for Android 2.0 and above
// parameters.setRotation(90);
} else {
// This is an undocumented although widely known feature
parameters.set("orientation", "landscape");
// For Android 2.2 and above
camera.setDisplayOrientation(0);
// Uncomment for Android 2.0 and above
// parameters.setRotation(0);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
} catch (IOException exception) {
camera.release();
Log.v("surfaceCreated", exception.getMessage());
}
camera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
}
#Override
public void onPictureTaken(final byte[] data, Camera camera) {
this.addContentView(viewControl, layoutParamsControl);
save.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
insertImage(data);
Intent i = new Intent();
i.putExtra("data", imageFileUri.toString());
setResult(-1, i);
finish();
}});
retry.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}});
}
public void insertImage(byte[] data)
{
Bitmap b = null;
try {
b = GeneralUtils.decodeFile(data, this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 80, bos);
//b = null;
Bitmap bitmap = BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.size());
Matrix m = new Matrix();
if (b.getWidth() > b.getHeight())
{
m.postRotate(90);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
}
String result = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "", "");
b.recycle();
data = null;
b = null;
m = null;
imageFileUri = Uri.parse(result);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(null, null, null, this);
}
}

Categories