android custom camera orientation issue [duplicate] - android

This question already has answers here:
Camera preview is in portrait mode but image captured is rotated
(3 answers)
Closed 6 years ago.
I have defined a custom camera view to take picture.
The issue i am getting is if the picture is taken with camera held in "portrait" , the image is 90 rotated. If i take the picture in "landscape" mode, it is getting correct .
My code is below . I tried few solutions like Android - Camera preview is sideways
but it didnt fix my problem.
Please give me some directions.
Thanks.
public class Customcamera extends Activity implements OnClickListener {
private SurfaceView preview = null;
private SurfaceHolder previewHolder = null;
private Camera camera = null;
private boolean inPreview = false;
Bitmap bmp;
static Bitmap mutableBitmap;
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
File imageFileName = null;
File imageFileFolder = null;
private MediaScannerConnection msConn;
Display d;
int screenhgt, screenwdh;
ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preview);
preview = (SurfaceView) findViewById(R.id.surface);
previewHolder = preview.getHolder();
previewHolder.addCallback(surfaceCallback);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
previewHolder.setFixedSize(getWindow().getWindowManager()
.getDefaultDisplay().getWidth(), getWindow().getWindowManager()
.getDefaultDisplay().getHeight());
}
#Override
public void onResume() {
super.onResume();
camera = Camera.open();
setCameraDisplayOrientation(this, 0, camera);
}
#Override
public void onPause() {
if (inPreview) {
camera.stopPreview();
}
camera.release();
camera = null;
inPreview = false;
super.onPause();
}
private Camera.Size getBestPreviewSize(int width, int height,
Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.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);
}
SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
public void surfaceCreated(SurfaceHolder holder) {
try {
camera.setPreviewDisplay(previewHolder);
} catch (Throwable t) {
Log.e("PreviewDemo-surfaceCallback",
"Exception in setPreviewDisplay()", t);
Toast.makeText(Customcamera.this, t.getMessage(),
Toast.LENGTH_LONG).show();
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = getBestPreviewSize(width, height, parameters);
if (size != null) {
parameters.setPreviewSize(size.width, size.height);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
setCameraDisplayOrientation(Customcamera.this, 0, camera);
camera.setParameters(parameters);
camera.startPreview();
inPreview = true;
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// no-op
}
};
Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
public void onPictureTaken(final byte[] data, final Camera camera) {
Log.i("onPictureTaken", "onPictureTaken");
dialog = ProgressDialog.show(Customcamera.this, "", "Saving Photo");
/*
* new Thread() { public void run() { try { // Thread.sleep(1000); }
* catch (Exception ex) { } onPictureTake(data, camera); }
* }.start();
*/
onPictureTake(data, camera);
}
};
public void onPictureTake(byte[] data, Camera camera) {
if (mutableBitmap != null) {
mutableBitmap.recycle();
}
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
mutableBitmap = bmp.copy(Bitmap.Config.ARGB_8888, true);
savePhoto(mutableBitmap);
showPhoto();
dialog.dismiss();
}
private void showPhoto() {
Intent intent = new Intent(this, EditAndPostActivity.class);
startActivity(intent);
}
class SavePhotoTask extends AsyncTask<byte[], String, String> {
#Override
protected String doInBackground(byte[]... jpeg) {
File photo = new File(Environment.getExternalStorageDirectory(),
"photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos = new FileOutputStream(photo.getPath());
fos.write(jpeg[0]);
fos.close();
} catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
return (null);
}
}
public void savePhoto(Bitmap bmp) {
imageFileFolder = new File(Environment.getExternalStorageDirectory(),
"Unipyx");
imageFileFolder.mkdir();
FileOutputStream out = null;
Calendar c = Calendar.getInstance();
String date = fromInt(c.get(Calendar.MONTH))
+ fromInt(c.get(Calendar.DAY_OF_MONTH))
+ fromInt(c.get(Calendar.YEAR))
+ fromInt(c.get(Calendar.HOUR_OF_DAY))
+ fromInt(c.get(Calendar.MINUTE))
+ fromInt(c.get(Calendar.SECOND));
imageFileName = new File(imageFileFolder, date.toString() + ".jpg");
try {
out = new FileOutputStream(imageFileName);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
scanPhoto(imageFileName.toString());
out = null;
} catch (Exception e) {
e.printStackTrace();
}
}
public String fromInt(int val) {
return String.valueOf(val);
}
public void scanPhoto(final String imageFileName) {
msConn = new MediaScannerConnection(Customcamera.this,
new MediaScannerConnectionClient() {
public void onMediaScannerConnected() {
msConn.scanFile(imageFileName, null);
Log.i("msClient obj in Photo Utility",
"connection established");
}
public void onScanCompleted(String path, Uri uri) {
msConn.disconnect();
Log.i("msClient obj in Photo Utility", "scan completed");
}
});
msConn.connect();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
onBack();
}
return super.onKeyDown(keyCode, event);
}
public void onBack() {
Log.e("onBack :", "yes");
camera.takePicture(null, null, photoCallback);
inPreview = false;
}
#Override
public void onClick(View v) {
}
public static void setCameraDisplayOrientation(Activity activity,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().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;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
}

When you convert the byte[] to a Bitmap in onPictureTake(), you are throwing away the orientation information included in the byte array. You should instead directly write the bytes to a File if you want to save the orientation information.

Related

How to rotate the captured image using Camera class

I am trying to implement a custom camera by using Camera class and SurfaceView. But the image taken by camera gets rotated. The preview in SurfaceView was also rotating but in the code i have fixed it by using the setCameraDisplayOrientation() method.Below are the images that gets generated in the screen & i took screenshots.
surfaceView: ImageView:
And the code i am using is:
public class CustomCameraActivity extends AppCompatActivity implements PictureCallback, SurfaceHolder.Callback
{
private Camera mCamera;
private ImageView mCameraImage;
private SurfaceView mCameraPreview;
private Button mCaptureImageButton;
private byte[] mCameraData;
private boolean mIsCapturing;
private OnClickListener mCaptureImageButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
App.getInstance().setCapturedPhotoData(null);
captureImage();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_camera);
mImgViewCover = (ImageView) findViewById(R.id.imgVw_customCameraCover);
mCameraImage = (ImageView) findViewById(R.id.camera_image_view);
mCameraImage.setVisibility(View.INVISIBLE);
mCameraPreview = (SurfaceView) findViewById(R.id.preview_view);
final SurfaceHolder surfaceHolder = mCameraPreview.getHolder();
surfaceHolder.addCallback(this);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mCaptureImageButton = (Button) findViewById(R.id.capture_image_button);
mCaptureImageButton.setOnClickListener(mCaptureImageButtonClickListener);
mIsCapturing = true;
}
#Override
protected void onResume() {
super.onResume();
if (mCamera == null) {
try {
mCamera = Camera.open();
mCamera.setPreviewDisplay(mCameraPreview.getHolder());
if (mIsCapturing) {
mCamera.startPreview();
}
} catch (Exception e) {
Toast.makeText(CustomCameraActivity.this, "Unable to open camera.", Toast.LENGTH_LONG)
.show();
}
}
}
#Override
protected void onPause() {
super.onPause();
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
mCameraData = data;
setupImageDisplay();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (holder.getSurface() == null)
return;
try { mCamera.stopPreview();
} catch (Exception e) { }
if (mCamera != null) {
try {
Camera.Parameters parameters = mCamera.getParameters();
List<Size> sizes = parameters.getSupportedPreviewSizes();
Size optimalSize = getOptimalPreviewSize(sizes, width, height);
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
mCamera.setParameters(parameters);
setCameraDisplayOrientation(this, Camera.CameraInfo.CAMERA_FACING_BACK, mCamera );
if (mIsCapturing) {
mCamera.startPreview();
}
} catch (Exception e) {
Toast.makeText(CustomCameraActivity.this, "Unable to start camera preview.", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder)
{
try {
mCamera = Camera.open();
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mCamera != null)
{ mCamera.stopPreview();
mCamera.release();
mCamera = null;}
}
private void captureImage() {
mCamera.takePicture(null, null, this);
}
private void setupImageCapture() {
mCameraImage.setVisibility(View.INVISIBLE);
mCameraPreview.setVisibility(View.VISIBLE);
mCamera.startPreview();
mCaptureImageButton.setText("capture image");
mCaptureImageButton.setOnClickListener(mCaptureImageButtonClickListener);
}
private void setupImageDisplay() {
Bitmap bitmap = BitmapFactory.decodeByteArray(mCameraData, 0, mCameraData.length);
mCameraImage.setImageBitmap(bitmap);
mCamera.stopPreview();
mCameraPreview.setVisibility(View.INVISIBLE);
mCameraImage.setVisibility(View.VISIBLE);
if (mCameraData != null) {
Intent intent = new Intent();
intent.putExtra(EXTRA_CAMERA_DATA, mCameraData);
setResult(RESULT_OK, intent);
} else {
setResult(RESULT_CANCELED);
}
}
private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.5;
double targetRatio = (double) w / h;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
public static void setCameraDisplayOrientation(Context context,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = ((Activity)context).getWindowManager().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;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
// camera.getParameters().setRotation(result);
}
}
I can rotate the bitmap to 90 before showing in imageview -by using the code:
public static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}
But it shouldn't be the proper way to solve it. So, how do i fix this and show the non-rotated image in imageView?
Use this way to open camera using surface view Java Code
public class CameraOverlayActivity extends AppCompatActivity implements SurfaceHolder.Callback {
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
private File videoPath;
private ImageView imgCapture;
int camBackId;
String strVideoFolderPath;
private ProgressDialog progressDialog;
Camera.Parameters parameters;
public boolean hasFlash;
public boolean camRotation = false;
private RelativeLayout relativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_overlay);
relativeLayout = findViewById(R.id.control);
camBackId = Camera.CameraInfo.CAMERA_FACING_BACK;
hasFlash = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
surfaceView = findViewById(R.id.surface);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle(null);
progressDialog.setCancelable(false);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
strVideoFolderPath = Environment.getExternalStorageDirectory().getAbsolutePath();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
videoPath = new File(Environment.getExternalStorageDirectory() + "/sw/raw");
if (videoPath.exists()) {
if (videoPath.isDirectory()) {
if (videoPath.listFiles().length != 0) {
String[] children = videoPath.list();
for (int i = 0; i < children.length; i++) {
new File(videoPath, children[i]).delete();
}
}
}
}
if (!videoPath.exists()) {
videoPath.mkdirs();
}
imgCapture = findViewById(R.id.img_capture);
imgCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (camera != null) {
if (previewing) {
System.gc();
try {
capturePhoto();
} catch (Exception e) {
Log.v("ERRORR", e.getMessage());
e.printStackTrace();
}
}
}
}
});
}
public void capturePhoto() throws Exception {
camera.takePicture(null, null, myPictureCallback_JPG);
}
#Override
protected void onResume() {
super.onResume();
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
}
Camera.PictureCallback myPictureCallback_JPG = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
FileOutputStream outStream = null;
//camera.startPreview();
try {
Date date = new Date();
String filename = "/rec" + date.toString().replace(" ", "_").replace(":", "_") + ".jpg";
filename = filename.replace("+", "");
File file = new File(Environment.getExternalStorageDirectory() + "/Switch It");
if (!file.exists())
file.mkdirs();
outStream = new FileOutputStream(file + filename);
outStream.write(arg0);
outStream.close();
Log.v("File_Path", file.getAbsolutePath());
Intent returnIntent = new Intent();
returnIntent.putExtra("img_capture", file.getAbsolutePath() + filename);
setResult(Activity.RESULT_OK, returnIntent);
finish();
} catch (FileNotFoundException e) {
Log.e("ERROR 1", e.getMessage());
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
Log.e("ERROR 2", e.getMessage());
} finally {
}
}
};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if (previewing) {
camera.stopPreview();
previewing = false;
}
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
parameters = camera.getParameters();
if (getPackageManager().hasSystemFeature("android.hardware.camera.autofocus")) {
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
}
camera.startPreview();
if (hasFlash) {
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
}
camera.setParameters(parameters);
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
if (android.os.Build.VERSION.SDK_INT > 7) {
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
if (display.getRotation() == Surface.ROTATION_0) {
camera.setDisplayOrientation(90);
camRotation = true;
}
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
}
Rotate your imageview on angle whenever your image not rotated as per your requirement You can rotate your ImageView Using this
mImageView.setRotation(yourRequiredAngle)
Hope it helps.

How resize the image bitmap with the custom layout height and width

I am using the fallowing solution to resize the bitmap. But it results portion of the image is lost.
Here is is my code.
BitmapFactory.Options bmFactoryOptions = new BitmapFactory.Options();
bmFactoryOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
bmFactoryOptions.inMutable = true;
bmFactoryOptions.inSampleSize = 2;
Bitmap originalCameraBitmap = BitmapFactory.decodeByteArray(pData, 0, pData.length, bmFactoryOptions);
rotatedBitmap = getResizedBitmap(originalCameraBitmap, cameraPreviewLayout.getHeight(), cameraPreviewLayout.getWidth() - preSizePriviewHight(), (int) rotationDegrees);
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight, int angle) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postRotate(angle);
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
DeliverItApplication.getInstance().setImageCaptured(true);
return resizedBitmap;
}
And here is the image height and width : Preview surface size:352:288 Before resized bitmap width : 320 Height : 240 CameraPreviewLayout width : 1080 Height : 1362 Resized bitmap width : 1022 Height : 1307
Your java code is right but you haven't care about Aspect Ratio of Image thats whys your Image Portion is cutting.
Original Image Height and Width :
Height = 352;
Width = 288;
Aspect Ratio = h/w; => Ratio = 1.2;
and you taken new width and height :
newHeight = 320;
newWidth = 240;
But if we take Image Height as 320 then according Image Aspect Ratio Its Width becomes :
calculated width = newHeight /Ratio; => 320/1.2= 266.66= 267;
calculated width = 267;
difference of portion cutting is = calculated width -newWidth;
= 267 -240 ;
= 27 ;
So you need to take height and width for new bitmap.
newHeight = 320;
newWidth = 267 ;
public class MarkableImageCaptureActivity extends Activity implements OnClickListener {
private static Logger logger = LoggerFactory.getLogger(MarkableImageCaptureActivity.class);
#InjectView(R.id.top_menu_bar)
private LinearLayout topMenuLayout;
#InjectView(R.id.top_menu_title)
private TextView topMenuTitleTV;
#InjectView(R.id.image_desc_edittext)
private EditText imageDescEditText;
#InjectView(R.id.camerapreview_layout)
private FrameLayout cameraPreviewLayout;
#InjectView(R.id.btn_camera_capture)
private Button captureBtn;
#InjectView(R.id.btn_camera_save)
private Button saveBtn;
#InjectView(R.id.btn_camera_cancel)
private Button cancelBtn;
#InjectView(R.id.edit_captured_image_layout)
private RelativeLayout editCapturedImageLayout;
#InjectView(R.id.edit_captured_image)
private ImageView editCapturedImage;
#InjectView(R.id.color_container_layout)
private LinearLayout colorContainerLayout;
#InjectView(R.id.btn_markable_red)
private Button btnMarkableRed;
#InjectView(R.id.btn_markable_blue)
private Button btnMarkableBlue;
#InjectView(R.id.btn_markable_green)
private Button btnMarkableGreen;
#InjectView(R.id.btn_markable_white)
private Button btnMarkableWhite;
#InjectView(R.id.btn_markable_black)
private Button btnMarkableBlack;
#InjectView(R.id.btn_undo)
private TextView capturedImageUndo;
private MarkableImageView editableCapturedImageview;
#InjectView(R.id.flashSwitch)
private ToggleButton flashToggle;
private static final int DIALOG_CAPTURE_EXCEPTION = 2101;
private static final int DIALOG_CAPTURING_EXCEPTION = 2102;
private static final int DIALOG_SAVE_EXCEPTION = 0;
private String imageFileName = null;
private File imageFile = null;
private Stop targetStop = null;
private int stopId = DIntent.VALUE_INVALID_ID;
private float rotationDegrees = 0;
private Camera camera = null;
private CameraPreview cameraPreview;
private Bitmap rotatedBitmap;
private static final int PRIMARY_CAMERA_ID = 0;
private boolean imageCaptured = false;
private boolean inPreview = false;
private boolean isFlashSupports;
private boolean isCapturing = false;
private boolean isFlashOn;
private boolean isDocNameEditable;
private String imageDesc = "";
private Handler focusHandler = null;
private int captureType;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_start_camera_for_photo_capture);
setupTopMenuBar(topMenuLayout, null, getString(R.string.menuitem_back), getString(R.string.menuitem_done), true, true, new ImageCaptureTopMenuListener());
focusHandler = new Handler();
editableCapturedImageview = (MarkableImageView) findViewById(R.id.editable_captured_imageview);
Bundle intentBundle = getIntent().getExtras();
isDocNameEditable = getIntent().getBooleanExtra(DIntent.EXTRA_OBJECT_TYPE_DOCUMENT_EDITABLE, false);
imageDesc = getIntent().getStringExtra(DIntent.EXTRA_OBJECT_TYPE_DOCUMENT_NAME);
if (savedInstanceState != null) {
stopId = savedInstanceState.getInt(DIntent.EXTRA_STOP_ID);
imageDesc = savedInstanceState.getString(DIntent.EXTRA_IMAGE_DESC);
imageCaptured = savedInstanceState.getBoolean(DIntent.EXTRA_IS_IMAGE_CAPTURED);
inPreview = savedInstanceState.getBoolean(DIntent.EXTRA_IN_PREVIEW);
isFlashOn=savedInstanceState.getBoolean(DIntent.FLASH_MODE_ON);
if (imageCaptured) {
rotatedBitmap = savedInstanceState.getParcelable(DIntent.EXTRA_IMAGE_BITMAP);
}
}
captureType = intentBundle.getInt(DIntent.EXTRA_TYPE_CAPTURE);
if (captureType == DIntent.EXTRA_TYPE_IMAGE_CAPTURE) {
stopId = intentBundle.getInt(DIntent.EXTRA_STOP_ID);
try {
targetStop = getDbHelper().getStopDao().queryForId(stopId);
} catch (SQLException e) {
logger.error("Exception finding stop by Id!!", e);
}
}
isFlashSupports = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (isFlashSupports) {
flashToggle.setVisibility(View.VISIBLE);
flashToggle.setOnClickListener(this);
} else {
flashToggle.setVisibility(View.GONE);
}
captureBtn.setOnClickListener(this);
saveBtn.setOnClickListener(this);
cancelBtn.setOnClickListener(this);
imageDescEditText.setText(imageDesc);
if (AndroidUtility.isValidTrimmedString(imageDesc)) {
if (!isDocNameEditable) {
imageDescEditText.setEnabled(false);
}
} else {
imageDescEditText.setEnabled(true);
}
editCapturedImage.setOnClickListener(this);
btnMarkableWhite.setOnClickListener(this);
btnMarkableRed.setOnClickListener(this);
btnMarkableBlue.setOnClickListener(this);
btnMarkableGreen.setOnClickListener(this);
btnMarkableBlack.setOnClickListener(this);
capturedImageUndo.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
logger.info("onStart:imageCaptured" + imageCaptured);
boolean isImageCaptured = DeliverItApplication.getInstance().isImageCaptured();
if (!isImageCaptured) {
if (rotatedBitmap != null) {
activateCapturedImageView(rotatedBitmap);
} else {
activatePreviewLayout();
}
}
}
private void activateCapturedImageView(Bitmap rotatedBitmap) {
cameraPreviewLayout.setVisibility(View.GONE);
editableCapturedImageview.setCapturedBitmap(rotatedBitmap);
editableCapturedImageview.setVisibility(View.VISIBLE);
editCapturedImageLayout.setVisibility(View.VISIBLE);
captureBtn.setVisibility(View.GONE);
saveBtn.setVisibility(View.VISIBLE);
saveBtn.requestFocus();
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) editableCapturedImageview.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
layoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
layoutParams.width = rotatedBitmap.getWidth();
layoutParams.height = rotatedBitmap.getHeight();
editableCapturedImageview.setLayoutParams(layoutParams);
logger.info("Inside activateCapturedImageView");
releaseCamera();
}
private void activatePreviewLayout() {
logger.info("Insie activatePreviewLayout");
cameraPreviewLayout.setVisibility(View.VISIBLE);
editableCapturedImageview.setVisibility(View.GONE);
editCapturedImageLayout.setVisibility(View.GONE);
captureBtn.setVisibility(View.VISIBLE);
captureBtn.requestFocus();
saveBtn.setVisibility(View.GONE);
}
#Override
protected void onResume() {
super.onResume();
logger.info("onResume");
if (rotatedBitmap == null || inPreview) {
activateCameraPreview();
}
}
public void activateCameraPreview() {
logger.info("activateCameraPreview");
camera = getCameraInstance(camera);
if (camera != null) {
cameraPreview = new CameraPreview(this, camera);
rotationDegrees = getCameraDisplayOrientation(this, PRIMARY_CAMERA_ID);
camera.setDisplayOrientation((int) rotationDegrees);
cameraPreviewLayout.addView(cameraPreview);
inPreview = true;
isCapturing = false;
Camera.Parameters params = camera.getParameters();
if (isFlashSupported(params)) {
logger.info("activateCameraPreview: Flash Mode:"+ isFlashOn);
if (isFlashOn) {
params.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
} else {
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
}
} else {
flashToggle.setVisibility(View.GONE);
}
camera.setParameters(params);
enableAutoFocusMode(camera);
}
}
private Runnable doFocusRunnable = new Runnable() {
#Override
public void run() {
if (camera != null) {
focusHandler.removeCallbacks(doFocusRunnable);
if (CameraPreview.isCameraPreviewStarted) {
try {
camera.autoFocus(autoFocusCallback);
logger.info("doFocusRunnable autofocus set");
} catch (Exception e) {
logger.error("Error while calling autofocus in camera."+e);
}
} else {
logger.info("doFocusRunnable isCameraPreviewStarted false. Postdelay for 2 seconds");
focusHandler.postDelayed(doFocusRunnable, 2000);
}
}
}
};
Camera.AutoFocusCallback autoFocusCallback = new Camera.AutoFocusCallback(){
#Override
public void onAutoFocus(boolean arg0, Camera arg1) {
if (camera != null) {
logger.info("Excuting onAutoFocus callback");
focusHandler.postDelayed(doFocusRunnable, 2000);
}
}
};
public Camera getCameraInstance(Camera oldCamera) {
Camera newCamera = null;
try {
logger.info("attempt to get a Camera instance");
if (oldCamera == null) {
logger.info("oldCamera is null.Opening Camera");
newCamera = Camera.open(PRIMARY_CAMERA_ID);
} else {
logger.info("oldCamera is not null.Releasing it and Opening Camera");
oldCamera.release();
newCamera = Camera.open(PRIMARY_CAMERA_ID);
}
} catch (Exception e) {
logger.info("Camera is not available (in use or does not exist)");
}
return newCamera; // returns null if camera is unavailable
}
#Override
protected void onPause() {
super.onPause();
logger.info("onPause");
releaseCamera();
}
private void releaseCamera() {
if (null != camera) {
try {
focusHandler.removeCallbacks(doFocusRunnable);
CameraPreview.isCameraPreviewStarted = false;
camera.cancelAutoFocus();
camera.stopPreview();
camera.release();
camera = null;
cameraPreview.setVisibility(View.GONE);
cameraPreview = null;
inPreview = false;
logger.info("Camera released successfully ");
} catch (Exception e) {
logger.error("Error while releasing camera in releaseCamera()."+e);
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
logger.info("onSaveInstanceState");
outState.putInt(DIntent.EXTRA_STOP_ID, stopId);
outState.putBoolean(DIntent.EXTRA_IS_IMAGE_CAPTURED, imageCaptured);
outState.putBoolean(DIntent.EXTRA_IN_PREVIEW, inPreview);
outState.putString(DIntent.EXTRA_IMAGE_DESC, imageDesc);
}
#Override
protected void onDestroy() {
super.onDestroy();
logger.info("onDestroy");
DeliverItApplication.getInstance().setImageCaptured(false);
}
public float getCameraDisplayOrientation(Activity activity, int cameraId) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(cameraId, info);
int displayOrientation = activity.getWindowManager().getDefaultDisplay().getRotation();
int infoOrientation = info.orientation;
float degrees = 0;
switch (displayOrientation) {
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;
}
float result;
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
logger.info("Camera.CameraInfo.CAMERA_FACING_FRONT");
result = (infoOrientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
logger.info("Camera.CameraInfo.CAMERA_FACING_BACK");
result = (infoOrientation - degrees + 360) % 360;
}
logger.info("Display Rotation:" + displayOrientation + " & infoOrientation:" + infoOrientation + " & degrees:"
+ degrees + " & info.facing:" + info.facing + " & result:" + result);
return result;
}
private void captureImage() {
try {
if (camera != null) {
//camera.autoFocus(autoFocusCallback);
isCapturing = true;
logger.info("Taking picture while clicking Capture button");
camera.takePicture(null, null, pictureCallBack);
} else {
if (rotatedBitmap == null) {
showDialog(DIALOG_CAMERA_UNAVAILABLE);
}
}
} catch (Exception e) {
releaseCamera();
logger.error("Error in camera initialization in StartCaptureForPhoto screen.");
activatePreviewLayout();
activateCameraPreview();
}
}
private PictureCallback pictureCallBack = new PictureCallback() {
#Override
public void onPictureTaken(byte[] pData, Camera pCamera) {
BitmapFactory.Options bmFactoryOptions = new BitmapFactory.Options();
bmFactoryOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
bmFactoryOptions.inMutable = true;
// bmFactoryOptions.inSampleSize = 2;
Bitmap originalCameraBitmap = BitmapFactory.decodeByteArray(pData, 0, pData.length, bmFactoryOptions);
logger.info("before resized bitmap width : "+originalCameraBitmap.getWidth() + " Hieght : "+ originalCameraBitmap.getHeight());
rotatedBitmap = getResizedBitmap(originalCameraBitmap, cameraPreviewLayout.getHeight(), cameraPreviewLayout.getWidth() - preSizePriviewHight(), (int) rotationDegrees);
logger.info("cameraPreviewLayout width : "+cameraPreviewLayout.getWidth() + " Hieght : "+ cameraPreviewLayout.getHeight());
if (rotatedBitmap != null) {
imageCaptured = true;
activateCapturedImageView(rotatedBitmap);
} else {
imageCaptured = false;
}
isCapturing = false;
originalCameraBitmap.recycle();
flashToggle.setVisibility(View.GONE);
}
};
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight, int angle) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postRotate(angle);
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
DeliverItApplication.getInstance().setImageCaptured(true);
return resizedBitmap;
}
#Override
public void onClick(View pView) {
switch (pView.getId()) {
case R.id.btn_camera_capture:
if (!isCapturing) {
captureImage();
} else {
logger.error("Picture being captured.User clicked so fast.");
}
break;
case R.id.btn_camera_save:
if (imageCaptured) {
String description = imageDescEditText.getText().toString();
if (description != null && description.length() > 0) {
saveCapturedImage();
} else {
imageDescEditText.setError((getString(R.string.error_photo_desc)));
}
}
break;
case R.id.edit_captured_image:
colorContainerLayout.setVisibility(View.VISIBLE);
capturedImageUndo.setVisibility(View.VISIBLE);
editableCapturedImageview.setPaintBrushColor(Color.WHITE);
break;
case R.id.btn_markable_green:
editableCapturedImageview.setPaintBrushColor(Color.parseColor("#6AD523"));
break;
case R.id.btn_markable_blue:
editableCapturedImageview.setPaintBrushColor(Color.parseColor("#407FF0"));
break;
case R.id.btn_markable_red:
editableCapturedImageview.setPaintBrushColor(Color.parseColor("#B0321B"));
break;
case R.id.btn_markable_white:
editableCapturedImageview.setPaintBrushColor(Color.parseColor("#F7F5FA"));
break;
case R.id.btn_markable_black:
editableCapturedImageview.setPaintBrushColor(Color.parseColor("#2A2A2C"));
break;
case R.id.btn_undo:
editableCapturedImageview.onClickUndo();
break;
case R.id.btn_camera_cancel:
releaseCamera();
finish();
break;
case R.id.flashSwitch:
switchFlash();
default:
break;
}
}
#Override
protected Dialog onCreateDialog(int id, Bundle bundle) {
switch (id) {
case DIALOG_CAPTURE_EXCEPTION:
DIAlertDialog captureErrorDialog = new DIAlertDialog(this, getText(R.string.dialog_camera_error)
.toString(), getText(R.string.dialog_capture_exception).toString(), null, null);
return captureErrorDialog;
case DIALOG_SAVE_EXCEPTION:
DIAlertDialog imageSaveErrorDialog = new DIAlertDialog(this, getText(R.string.dialog_camera_error)
.toString(), getText(R.string.dialog_image_save_exception).toString(), null, null);
return imageSaveErrorDialog;
case DIALOG_CAPTURING_EXCEPTION:
DIAlertDialog capturingDialog = new DIAlertDialog(this, getText(R.string.dialog_camera_error)
.toString(), getText(R.string.dialog_capturing_exception).toString(), null, null);
return capturingDialog;
default:
return super.onCreateDialog(id, bundle);
}
}
private class ImageCaptureTopMenuListener implements OnClickListener {
#Override
public void onClick(View v) {
if (v.getVisibility() == View.VISIBLE && v.getId() == R.id.top_left_menu_item) {
onBackPressed();
} else if (v.getVisibility() == View.VISIBLE && v.getId() == R.id.top_right_menu_item) {
if (imageCaptured) {
String description = imageDescEditText.getText().toString();
if (description != null && description.length() > 0) {
saveCapturedImage();
} else {
imageDescEditText.setError((getString(R.string.error_photo_desc)));
}
}
}
}
}
private void switchFlash() {
if (camera == null) {
return;
}
if (!isFlashOn) {
Camera.Parameters params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
camera.setParameters(params);
if (rotatedBitmap != null) {
activateCapturedImageView(rotatedBitmap);
} else {
activatePreviewLayout();
}
isFlashOn = true;
} else {
Camera.Parameters params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
if (rotatedBitmap != null) {
activateCapturedImageView(rotatedBitmap);
} else {
activatePreviewLayout();
}
isFlashOn = false;
}
}
private int preSizePriviewHight() {
int defaultSize = 100;
switch (getResources().getDisplayMetrics().densityDpi) {
case DisplayMetrics.DENSITY_LOW:
defaultSize = 75;
break;
case DisplayMetrics.DENSITY_MEDIUM:
defaultSize = 80;
break;
case DisplayMetrics.DENSITY_HIGH:
defaultSize = 120;
break;
case DisplayMetrics.DENSITY_XHIGH:
defaultSize = 160;
break;
case DisplayMetrics.DENSITY_XXHIGH:
defaultSize = 430;
break;
case DisplayMetrics.DENSITY_XXXHIGH:
defaultSize = 460;
break;
default:
break;
}
return defaultSize;
}
private void enableAutoFocusMode(Camera camera) {
try {
Camera.Parameters params = camera.getParameters();
List<String> focusParameterList = params.getSupportedFocusModes();
if (focusParameterList != null && focusParameterList.size() > 0) {
logger.info("Supported focus mode:"+focusParameterList);
if (focusParameterList.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
logger.info("enableAutoFocusMode: Starting focus mode");
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
camera.setParameters(params);
/*
Below line commented due to crash issue in focus mode because of autoFocus call before start preview
So we are giving 2 sec delay for autoFocus.
*/
//camera.autoFocus(autoFocusCallback);
focusHandler.postDelayed(doFocusRunnable, 2000);
}
}
} catch (Exception e) {
logger.error("Error while setting AutoFocus in Camera."+e);
}
}
private boolean isFlashSupported(Camera.Parameters params) {
if (params != null) {
List<String> flashModes = params.getSupportedFlashModes();
if(flashModes == null) {
return false;
}
for(String flashMode : flashModes) {
if(Camera.Parameters.FLASH_MODE_ON.equals(flashMode)) {
return true;
}
}
}
return false;
}
#Override
protected void onStop() {
super.onStop();
if (editableCapturedImageview != null) {
editableCapturedImageview.resetCanvas();
}
}
}
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static Logger logger = LoggerFactory.getLogger(CameraPreview.class);
private SurfaceHolder surfaceHolder;
private Camera camera;
private List<Size> cameraSizeList;
private Camera.Parameters cameraParameters;
public static boolean isCameraPreviewStarted = false;
public CameraPreview(Context context, Camera camera) {
super(context);
logger.info("Inside CameraPreview(Context context, Camera camera)");
this.camera = camera;
isCameraPreviewStarted = false;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
surfaceHolder = getHolder();
surfaceHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
try {
if (camera != null) {
logger.info("Camera Surface has been created, now tell the camera where to draw the preview.");
camera.setPreviewDisplay(holder);
camera.startPreview();
isCameraPreviewStarted = true;
}
} catch (IOException e) {
logger.error("Error occured in surfaceCreated.", e);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
logger.info("Camera SurfaceView Destroyed.");
isCameraPreviewStarted = false;
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (surfaceHolder.getSurface() == null) {
if (logger.isDebugEnabled()) {
logger.debug("onsurfaceChanged : preview surface does not exist");
}
return;
}
try {
if (logger.isDebugEnabled()) {
logger.debug("onsurfaceChanged :stop preview before making resize/rotate/reformatting changes");
}
isCameraPreviewStarted = false;
camera.stopPreview();
} catch (Exception e) {
logger.error("onsurfaceChanged :Ignored surfaceChanged because tried to stop a non-existent preview", e);
}
if (camera != null) {
cameraParameters = camera.getParameters();
cameraSizeList = cameraParameters.getSupportedPreviewSizes();
cameraParameters.setPreviewSize(getMaxSupportedVideoSize().width, getMaxSupportedVideoSize().height);
surfaceHolder.setFixedSize(getMaxSupportedVideoSize().width, getMaxSupportedVideoSize().height);
camera.setParameters(cameraParameters);
if (logger.isDebugEnabled()) {
logger.debug("onsurfaceChanged : made resize/rotate/reformatting changes:preview size:"
+ String.valueOf(getMaxSupportedVideoSize().width) + ":"
+ String.valueOf(getMaxSupportedVideoSize().height));
}
}
try {
if (logger.isDebugEnabled()) {
logger.debug("onsurfaceChanged :start preview with new settings");
}
if (camera != null) {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
logger.info("onsurfaceChanged :start preview with new settings");
isCameraPreviewStarted = true;
}
} catch (Exception e) {
logger.error("onsurfaceChanged :Error while resetting camera preview on surfaceChanged.", e);
}
}
public Size getMaxSupportedVideoSize() {
int maximum = cameraSizeList.get(0).width;
int position = 0;
for (int i = 0; i < cameraSizeList.size() - 1; i++) {
if (cameraSizeList.get(i).width > maximum) {
maximum = cameraSizeList.get(i).width; // new maximum
position = i - 1;
}
}
if (position == 0) {
int secondMax = cameraSizeList.get(1).width;
position = 1;
for (int j = 1; j < cameraSizeList.size() - 1; j++) {
if (cameraSizeList.get(j).width > secondMax) {
secondMax = cameraSizeList.get(j).width; // new maximum
position = j;
}
}
}
return cameraSizeList.get(position);
}
}

Camera Preview landscape view not fullscreen

I've searched stack exchange and google for a solution but I can't seem to find one that works. My camera preview works beautifully in portrait, but when the orientation switches to landscape, it is not full screen and is highly distorted. I'm also trying to implement this as a fragment
Here is my code
CameraFragment.java
public class CameraFragment extends Fragment implements SurfaceHolder.Callback, Camera.PictureCallback {
public static final String TAG = CameraFragment.class.getSimpleName();
private static final int PICTURE_SIZE_MAX_WIDTH = 1280;
private static final int PREVIEW_SIZE_MAX_WIDTH = 640;
private int cameraId;
private Camera camera;
private SurfaceHolder surfaceHolder;
private CameraFragmentListener listener;
private int displayOrientation;
private int layoutOrientation;
private CameraOrientationListener orientationListener;
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
if(!(activity instanceof CameraFragmentListener)){
throw new IllegalArgumentException("Must implement CameraFragmentListener interface");
}
listener = (CameraFragmentListener)activity;
orientationListener = new CameraOrientationListener(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
CameraPreview previewView = new CameraPreview(getActivity());
previewView.getHolder().addCallback(this);
return previewView;
}
#Override
public void onResume() {
super.onResume();
orientationListener.enable();
try {
camera = Camera.open(cameraId);
} catch (Exception exception) {
Log.e(TAG, "Can't open camera with id " + cameraId, exception);
listener.onCameraError();
return;
}
}
#Override
public void onPause() {
super.onPause();
orientationListener.disable();
if(camera != null) {
stopCameraPreview();
camera.release();
}
}
private synchronized void startCameraPreview() {
determineDisplayOrientation();
setupCamera();
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (Exception exception) {
Log.e(TAG, "Can't start camera preview due to Exception", exception);
listener.onCameraError();
}
}
private synchronized void stopCameraPreview() {
try {
camera.stopPreview();
} catch (Exception exception) {
Log.i(TAG, "Exception during stopping camera preview");
}
}
public void determineDisplayOrientation() {
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, cameraInfo);
int rotation = getActivity().getWindowManager().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;
}
int displayOrientation;
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
displayOrientation = (cameraInfo.orientation + degrees) % 360;
displayOrientation = (360 - displayOrientation) % 360;
} else {
displayOrientation = (cameraInfo.orientation - degrees + 360) % 360;
}
this.displayOrientation = displayOrientation;
this.layoutOrientation = degrees;
camera.setDisplayOrientation(displayOrientation);
}
public void setupCamera() {
Camera.Parameters parameters = camera.getParameters();
Camera.Size bestPreviewSize = determineBestPreviewSize(parameters);
Camera.Size bestPictureSize = determineBestPictureSize(parameters);
parameters.setPreviewSize(bestPreviewSize.width, bestPreviewSize.height);
parameters.setPictureSize(bestPictureSize.width, bestPictureSize.height);
camera.setParameters(parameters);
}
private Camera.Size determineBestPreviewSize(Camera.Parameters parameters) {
List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
return determineBestSize(sizes, PREVIEW_SIZE_MAX_WIDTH);
}
private Camera.Size determineBestPictureSize(Camera.Parameters parameters) {
List<Camera.Size> sizes = parameters.getSupportedPictureSizes();
return determineBestSize(sizes, PICTURE_SIZE_MAX_WIDTH);
}
protected Camera.Size determineBestSize(List<Camera.Size> sizes, int widthThreshold) {
Camera.Size bestSize = null;
for (Camera.Size currentSize : sizes) {
boolean isDesiredRatio = (currentSize.width / 4) == (currentSize.height / 3);
boolean isBetterSize = (bestSize == null || currentSize.width > bestSize.width);
boolean isInBounds = currentSize.width <= PICTURE_SIZE_MAX_WIDTH;
if (isDesiredRatio && isInBounds && isBetterSize) {
bestSize = currentSize;
}
}
if (bestSize == null) {
listener.onCameraError();
return sizes.get(0);
}
return bestSize;
}
public void takePicture(){
orientationListener.rememberOrientation();
camera.takePicture(null, null, this);
}
#Override
public void onPictureTaken(byte[] data, Camera camera){
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
int rotation = (displayOrientation + orientationListener.getRememberedOrientation() + layoutOrientation) % 360;
if(rotation != 0){
Bitmap oldBitmap = bitmap;
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
oldBitmap.recycle();
}
listener.onPictureTaken(bitmap);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
this.surfaceHolder = holder;
startCameraPreview();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
//fragment handles release
}
}
CameraFragmentListener.java
public interface CameraFragmentListener {
public void onCameraError();
public void onPictureTaken(Bitmap bitmap);
}
CameraOrientationListener.java
public class CameraOrientationListener extends OrientationEventListener {
private int currentNormalizedOrientation;
private int rememberNormalizedOrientation;
public CameraOrientationListener (Context context){
super(context, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onOrientationChanged(int orientation) {
if(orientation != ORIENTATION_UNKNOWN){
currentNormalizedOrientation = normalize(orientation);
}
}
private int normalize(int degrees){
if(degrees > 315 || degrees <= 45)
return 0;
if(degrees > 45 && degrees <= 135)
return 90;
if(degrees > 135 && degrees <= 225)
return 180;
if(degrees > 225 && degrees <= 315)
return 270;
throw new RuntimeException("Wrong bruh");
}
public void rememberOrientation(){
rememberNormalizedOrientation = currentNormalizedOrientation;
}
public int getRememberedOrientation(){
return rememberNormalizedOrientation;
}
}
CameraPreview.java
public class CameraPreview extends SurfaceView {
private static final double ASPECT_RATIO = 3.0 / 4.0;
public CameraPreview(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CameraPreview(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CameraPreview(Context context) {
super(context);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = MeasureSpec.getSize(heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
if (width > height * ASPECT_RATIO) {
width = (int) (height * ASPECT_RATIO + .5);
} else {
height = (int) (width / ASPECT_RATIO + .5);
}
setMeasuredDimension(width, height);
}
}
CameraActivity.java
public class CameraActivity extends Activity implements CameraFragmentListener {
public static final String TAG = CameraActivity.class.getSimpleName();
private static final int PICTURE_QUALITY = 90;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
}
#Override
public void onCameraError(){
Toast.makeText(this, getString(R.string.toast_error_camera_preview), Toast.LENGTH_SHORT).show();
finish();
}
public void takePicture(View view){
view.setEnabled(false);
CameraFragment fragment = (CameraFragment)getFragmentManager().findFragmentById(R.id.camera_fragment);
fragment.takePicture();
}
public void onPictureTaken(Bitmap bitmap){
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
),
getString(R.string.app_name)
);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
showSavingPictureErrorToast();
return;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = new File(
mediaStorageDir.getPath() + File.separator + "MUSTACHE_"+ timeStamp + ".jpg"
);
try {
FileOutputStream stream = new FileOutputStream(mediaFile);
bitmap.compress(CompressFormat.JPEG, PICTURE_QUALITY, stream);
} catch (IOException exception) {
showSavingPictureErrorToast();
Log.w(TAG, "IOException during saving bitmap", exception);
return;
}
MediaScannerConnection.scanFile(
this,
new String[] { mediaFile.toString() },
new String[] { "image/jpeg" },
null
);
Intent intent = new Intent(this, PhotoActivity.class);
intent.setData(Uri.fromFile(mediaFile));
startActivity(intent);
finish();
}
private void showSavingPictureErrorToast() {
Toast.makeText(this, getText(R.string.toast_error_save_picture), Toast.LENGTH_SHORT).show();
}
}
Sorry for the extremely long post, I just want to be as thorough as possible. Thanks in advance guys!
If you want your preview to be full screen, you should set the full screen flag in your activity before you call setContentView:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_camera);
}

Android camera app freezes black screen after onResume()

I am developing an app that is going to be something like camscanner. In my app i have an camera api tha i call. When the app is first opened and i press the camera button it works, but when i click home button and open again my app it freezes and shows a black screen without the app crashing. I found similar questions but none could give me a right answer, i know i probably have to change something in the onResume or onPause and need help to figure out what.
below i have my CameraScreen activity:
public class CameraScreen extends Activity {
ImageView image;
Activity context;
Preview preview;
Camera camera;
Button exitButton;
ImageView fotoButton;
LinearLayout progressLayout;
String path = "/sdcard/KutCamera/cache/images/";
FrameLayout frame;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_layout);
context=this;
fotoButton = (ImageView) findViewById(R.id.imageView_foto);
exitButton = (Button) findViewById(R.id.button_exit);
image = (ImageView) findViewById(R.id.imageView_photo);
progressLayout = (LinearLayout) findViewById(R.id.progress_layout);
preview = new Preview(this,
(SurfaceView) findViewById(R.id.KutCameraFragment));
frame = (FrameLayout) findViewById(R.id.preview);
frame.addView(preview);
preview.setKeepScreenOn(true);
fotoButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
takeFocusedPicture();
} catch (Exception e) {
}
exitButton.setClickable(true);
fotoButton.setClickable(false);
progressLayout.setVisibility(View.VISIBLE);
}
});
}
#Override
protected void onPause() {
super.onPause();
//releaseMediaRecorder(); // if you are using MediaRecorder, release it first
//releaseCamera();
if(null != camera){
camera.release();
camera = null;
}
frame.removeView(preview);
preview = null;// release the camera immediately on pause event
}
private void releaseCamera(){
if (camera != null){
camera.release(); // release the camera for other applications
camera = null;
}
}
#Override
protected void onResume() {
super.onResume();
// TODO Auto-generated method stub
if(camera==null){
Log.d("Camera tes", "Camera==null");
//camera.setPreviewCallback(null);
camera = Camera.open();
camera.startPreview();
camera.setErrorCallback(new ErrorCallback() {
public void onError(int error, Camera mcamera) {
camera.release();
camera = Camera.open();
Log.d("Camera died", "error camera");
}
});
}
if (camera != null) {
//camera.setPreviewCallback(null);
Log.d("Camera tes", "Camera!=null");
if (Build.VERSION.SDK_INT >= 14)
setCameraDisplayOrientation(context,
CameraInfo.CAMERA_FACING_BACK, camera);
preview.setCamera(camera);
}
}
private void setCameraDisplayOrientation(Activity activity, int cameraId,
android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().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;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
Camera.AutoFocusCallback mAutoFocusCallback = new Camera.AutoFocusCallback() {
#Override
public void onAutoFocus(boolean success, Camera camera) {
try{
camera.takePicture(mShutterCallback, null, jpegCallback);
}catch(Exception e){
}
}
};
Camera.ShutterCallback mShutterCallback = new ShutterCallback() {
#Override
public void onShutter() {
// TODO Auto-generated method stub
}
};
public void takeFocusedPicture() {
camera.autoFocus(mAutoFocusCallback);
}
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// Log.d(TAG, "onPictureTaken - raw");
}
};
PictureCallback jpegCallback = new PictureCallback() {
#SuppressWarnings("deprecation")
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
Calendar c = Calendar.getInstance();
File videoDirectory = new File(path);
if (!videoDirectory.exists()) {
videoDirectory.mkdirs();
}
try {
// Write to SD Card
outStream = new FileOutputStream(path + c.getTime().getSeconds() + ".jpg");
outStream.write(data);
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Bitmap realImage;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 5;
options.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
options.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
realImage = BitmapFactory.decodeByteArray(data,0,data.length,options);
ExifInterface exif = null;
try {
exif = new ExifInterface(path + c.getTime().getSeconds()
+ ".jpg");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Log.d("EXIF value",
exif.getAttribute(ExifInterface.TAG_ORIENTATION));
if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
.equalsIgnoreCase("1")) {
realImage = rotate(realImage, 90);
} else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
.equalsIgnoreCase("8")) {
realImage = rotate(realImage, 90);
} else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
.equalsIgnoreCase("3")) {
realImage = rotate(realImage, 90);
} else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
.equalsIgnoreCase("0")) {
realImage = rotate(realImage, 90);
}
} catch (Exception e) {
}
image.setImageBitmap(realImage);
fotoButton.setClickable(true);
camera.startPreview();
progressLayout.setVisibility(View.GONE);
exitButton.setClickable(true);
}
};
public static Bitmap rotate(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(),
source.getHeight(), matrix, false);
}
}
And here i have my Preview class:
class Preview extends ViewGroup implements SurfaceHolder.Callback {
private final String TAG = "Preview";
SurfaceView mSurfaceView;
SurfaceHolder mHolder;
int heightmax ;
int widthmax ;
Size mPreviewSize;
List<Size> mSupportedPreviewSizes;
Camera mCamera;
#SuppressWarnings("deprecation")
Preview(Context context, SurfaceView sv) {
super(context);
mSurfaceView = sv;
// addView(mSurfaceView);
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void setCamera(Camera camera) {
mCamera = camera;
if (mCamera != null) {
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPictureSizes();
requestLayout();
// get Camera parameters
Camera.Parameters params = mCamera.getParameters();
List<String> focusModes = params.getSupportedFocusModes();
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
// set the focus mode
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
// set Camera parameters
mCamera.setParameters(params);
}
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// We purposely disregard child measurements because act as a
// wrapper to a SurfaceView that centers the camera preview instead
// of stretching it.
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
if (mSupportedPreviewSizes != null) {
mPreviewSize=maxSize();
}
}
public Size maxSize(){
Size sizeMax=mSupportedPreviewSizes.get(0);
maxsize=mSupportedPreviewSizes.get(0)
.height*mSupportedPreviewSizes.get(0).width;
for(Size size:mSupportedPreviewSizes){
if(size.height*size.width>sizeMax.width*sizeMax.height){
sizeMax = size;
}
}
return sizeMax;
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (changed && getChildCount() > 0) {
final View child = getChildAt(0);
final int width = r - l;
final int height = b - t;
int previewWidth = width;
int previewHeight = height;
if (mPreviewSize != null) {
previewWidth = mPreviewSize.width;
previewHeight = mPreviewSize.height;
}
// Center the child SurfaceView within the parent.
if (width * previewHeight > height * previewWidth) {
final int scaledChildWidth = previewWidth * height / previewHeight;
child.layout((width - scaledChildWidth) / 2, 0,
(width + scaledChildWidth) / 2, height);
} else {
final int scaledChildHeight = previewHeight * width / previewWidth;
child.layout(0, (height - scaledChildHeight) / 2,
width, (height + scaledChildHeight) / 2);
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
try {
if (mCamera != null) {
mCamera.setPreviewDisplay(holder);
}
} catch (IOException exception) {
Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
/*
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
if (mCamera != null) {
mCamera.stopPreview();
}
*/
}
Camera.AutoFocusCallback mnAutoFocusCallback = new Camera.AutoFocusCallback() {
#Override
public void onAutoFocus(boolean success, Camera camera) {
}
};
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
/*
if(mCamera != null) {
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPictureSize(mPreviewSize.width, mPreviewSize.height);
requestLayout();
mCamera.setParameters(parameters);
mCamera.startPreview();
}
*/
}
}
I would appriciate any help or guides you can give me.

Android camera autofocus

I have a camera application in android.It's a custom camera. I want to use auto focus. But I can not do that. How to set auto focus and where I have to call. I tried a lot, but I can not able to fix it. Please help me.
Here is my custom camera activity:
public class CustomCameraActivity extends Activity implements
SurfaceHolder.Callback {
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
Context context;
Button btn1;
Button btn2;
ImageView imageView;
private Sensor mOrientaion1;
int cameraId = 0;
public final String TAG = "CustomCamera";
private OrientationEventListener orientationListener = null;
private SensorManager sensorManager;
float[] mGravs = new float[3];
float[] mGeoMags = new float[3];
float[] mRotationM = new float[16];
float[] mInclinationM = new float[16];
float[] mOrientation = new float[3];
float[] mOldOreintation = new float[3];
String[] mAccelerometer = new String[3];
String[] mMagnetic = new String[3];
String[] mRotation = new String[16];
String[] mInclination = new String[16];
String[] mOrientationString = new String[3];
String[] mOldOreintationString = new String[3];
#Override
public 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.main);
context = this;
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mOrientaion1 = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
orientationListener = new OrientationEventListener(this) {
public void onOrientationChanged(int orientation) {
setCameraDisplayOrientation(CustomCameraActivity.this, cameraId, camera);
}
};
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//imageView = (ImageView) findViewById(R.id.imgError);
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);
btn1 = (Button) viewControl.findViewById(R.id.Button01);
btn2 = (Button) viewControl.findViewById(R.id.Button02);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Toast.makeText(context, "1111111111111111111111111",
// Toast.LENGTH_SHORT).show();
camera.takePicture(null, null, mPicture);
btn1.setVisibility(View.INVISIBLE);
btn2.setVisibility(View.INVISIBLE);
Constant.rotationValueForCamera = Constant.rotationValue;
}
});
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Toast.makeText(context, "22222222222222222222222222",
// Toast.LENGTH_SHORT).show();
Log.e("0 imagePickerStatus", Constant.imagePickerStatus + "");
Constant.imagePickerStatus = 0;
Log.e("0 imagePickerStatus", Constant.imagePickerStatus + "");
finish();
}
});
this.addContentView(viewControl, layoutParamsControl);
int ot = getResources().getConfiguration().orientation;
if (Configuration.ORIENTATION_LANDSCAPE == ot) {
//imageView.setVisibility(View.GONE);
Log.e("ori1111", "land");
} else {
//imageView.setVisibility(View.VISIBLE);
Log.e("ori111", "port");
}
}
public String getPollDeviceAttitude() {
return Constant.rotationValueForCamera;
}
private SensorEventListener sensorEventListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravs = event.values.clone();// Fill gravityMatrix with accelerometer values
else if(event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeoMags = event.values.clone();// Fill geomagneticMatrix with magnetic-field sensor values
if(mGravs != null && mGeoMags != null){
mRotationM = new float[16];
mInclinationM = new float[16];
SensorManager.getRotationMatrix(mRotationM, mInclinationM, mGravs, mGeoMags);// Retrieve RMatrix, necessary for the getOrientation method
SensorManager.getOrientation(mRotationM, mOrientation);// Get the current orientation of the device
float r2d = 180f/(float)Math.PI;
DecimalFormat format = new DecimalFormat("#.##");
float[] ang = { 0.0f, mOrientation[1]*r2d, mOrientation[2]*r2d };
if ( ang[2] < 0.0f )
{
ang[2] = ang[2] + 90.0f;
}
else
{
ang[2] = 90 - ang[2];
ang[1] = -ang[1];
}
String x = format.format(ang[2]); //format.format(mOrientation[0]*r2d);
String y = format.format(ang[0]);
String z = format.format(ang[1]);
Constant.rotationValue =
x + " " +
y + " " +
z;
}
}
};
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener);
orientationListener.disable();
}
#Override
public void onResume() {
super.onResume();
btn1.setVisibility(View.VISIBLE);
btn2.setVisibility(View.VISIBLE);
sensorManager.registerListener(sensorEventListener,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(sensorEventListener,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(sensorEventListener,
sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_NORMAL);
if (Constant.isCapturedOk) {
Constant.isCapturedOk = false;
finish();
}
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Constant.imageData1 = data;
Log.e("Camrera", "22222222222222222");
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inDither = false;
// bfo.inJustDecodeBounds = true;
bfo.inPurgeable = true;
bfo.inTempStorage = new byte[16 * 1024];
Intent intent = new Intent(context, PreviewActivity.class);
// intent.putExtra("data", data);
Bitmap bitmapPicture = BitmapFactory.decodeByteArray(data, 0,
data.length, bfo);
Matrix matrix = new Matrix();
if (Constant.result == 0) {
matrix.postRotate(90);
}
if (Constant.result == 90) {
matrix.postRotate(0);
}
if (Constant.result == 180) {
matrix.postRotate(270);
}
if (Constant.result == 270) {
matrix.postRotate(180);
}
int height = bitmapPicture.getHeight();
int width = bitmapPicture.getWidth();
//Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmapPicture,
//height, width, true);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmapPicture, 0, 0,
bitmapPicture.getWidth(), bitmapPicture.getHeight(), matrix,
true);
ByteArrayOutputStream blob = new ByteArrayOutputStream();
Log.e("Camrera1", "22222222222222222");
rotatedBitmap.compress(CompressFormat.JPEG,
50 /* ignored for PNG */, blob);
byte[] bitmapdata = blob.toByteArray();
Constant.imageData = bitmapdata;
Log.e("Camrera2", "22222222222222222");
startActivity(intent);
overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
}
};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = getBestPreviewSize(width, height);
parameters.setPreviewSize(size.width, size.height); // preview size
camera.setParameters(parameters);
if (previewing) {
camera.stopPreview();
previewing = false;
}
if (camera != null) {
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
setCameraDisplayOrientation(this, 1, camera);
previewing = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void setCameraDisplayOrientation(Activity activity,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
Constant.result = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
Constant.result = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
Constant.result = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
Constant.result = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
if(camera != null)
camera.setDisplayOrientation(result);
}
private Camera.Size getBestPreviewSize(int width, int height)
{
// Get For Photo Size
Camera.Parameters camparams = camera.getParameters();
// Find the Largest Possible Preview Sizes
List<Size> sizes = camparams.getSupportedPreviewSizes();
Camera.Size result=null;
for (Size s : sizes) {
if (s.width <= width && s.height <= height) {
if (result == null) {
result = s;
} else {
int resultArea=result.width*result.height;
int newArea=s.width*s.height;
if (newArea>resultArea) {
result=s;
}
} // end else (result=null)
} // end if (width<width&&height<height)
} // end for
return result;
} // end function
#Override
public void surfaceCreated(SurfaceHolder holder) {
orientationListener.enable();
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
orientationListener.disable();
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
#Override
protected void onStop() {
super.onStop();
Log.e("Tab", "Stoping");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.onKeyDown(keyCode, event);
}
}
public class CustomCameraActivity extends Activity {
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
ProgressDialog dialog;
Bitmap bmp;
ImageView img;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(surfaceCallback);
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);
}
#Override
public void onResume() {
super.onResume();
camera = Camera.open();
}
#Override
public void onPause() {
if (previewing) {
camera.stopPreview();
}
camera.release();
camera = null;
previewing = false;
super.onPause();
}
SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
camera.setPreviewDisplay(surfaceHolder);
} catch (Throwable t) {
Log.e("PreviewDemo-surfaceCallback","Exception in setPreviewDisplay()", t);
Toast.makeText(CustomCameraActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Camera.Parameters parameters = camera.getParameters();
if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
parameters.set("orientation", "portrait");
camera.setDisplayOrientation(90);
parameters.setRotation(90);
}
else {
parameters.set("orientation", "landscape");
camera.setDisplayOrientation(0);
parameters.setRotation(0);
}
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
List<Size> sizes = parameters.getSupportedPictureSizes();
Camera.Size size = sizes.get(0);
for(int i=0;i<sizes.size();i++)
{
if(sizes.get(i).width > size.width)
size = sizes.get(i);
}
parameters.setPictureSize(size.width, size.height);
camera.setParameters(parameters);
camera.startPreview();
previewing = true;
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
};
Camera.AutoFocusCallback autoFocus=new AutoFocusCallback() {
ShutterCallback shutterCallback =new ShutterCallback() {
#Override
public void onShutter() {
AudioManager mgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mgr.playSoundEffect(AudioManager.FLAG_PLAY_SOUND);
}
};
Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
#Override
public void onPictureTaken(final byte[] data, final Camera camera) {
dialog = ProgressDialog.show(CustomCameraActivity.this, "", "Saving Photo");
new Thread() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (Exception ex) {}
onPictureTake(data, camera);
}
}.start();
}
};
#Override
public void onAutoFocus(boolean success, Camera camera) {
camera.takePicture(shutterCallback,null, null, photoCallback);
}
};
Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
#Override
public void onPictureTaken(final byte[] data, final Camera camera) {
dialog = ProgressDialog.show(CustomCameraActivity.this, "", "Saving Photo");
new Thread() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (Exception ex) {}
onPictureTake(data, camera);
}
}.start();
}
};
public void onPictureTake(byte[] data, Camera camera) {
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
dialog.dismiss();
}
public void AutoFocus(View v) {
camera.autoFocus(autoFocus);
}
}

Categories

Resources