I am creating an custom camera and when I click to take the pic, I am getting some errors.
I have used a SurfaceView to take the image.
Error:
10-10 16:17:00.269: E/AndroidRuntime(29256): FATAL EXCEPTION: main
10-10 16:17:00.269: E/AndroidRuntime(29256): Process: com.example.abc, PID: 29256
10-10 16:17:00.269: E/AndroidRuntime(29256): java.lang.RuntimeException: startPreview failed
10-10 16:17:00.269: E/AndroidRuntime(29256): at android.hardware.Camera.startPreview(Native Method)
10-10 16:17:00.269: E/AndroidRuntime(29256): at com.example.abc.Custom_CameraActivity.onClick(Custom_CameraActivity.java:237)
10-10 16:17:00.269: E/AndroidRuntime(29256): at android.view.View.performClick(View.java:4471)
10-10 16:17:00.269: E/AndroidRuntime(29256): at android.view.View$PerformClick.run(View.java:18778)
10-10 16:17:00.269: E/AndroidRuntime(29256): at android.os.Handler.handleCallback(Handler.java:808)
10-10 16:17:00.269: E/AndroidRuntime(29256): at android.os.Handler.dispatchMessage(Handler.java:103)
10-10 16:17:00.269: E/AndroidRuntime(29256): at android.os.Looper.loop(Looper.java:193)
10-10 16:17:00.269: E/AndroidRuntime(29256): at android.app.ActivityThread.main(ActivityThread.java:5304)
10-10 16:17:00.269: E/AndroidRuntime(29256): at java.lang.reflect.Method.invokeNative(Native Method)
10-10 16:17:00.269: E/AndroidRuntime(29256): at java.lang.reflect.Method.invoke(Method.java:515)
10-10 16:17:00.269: E/AndroidRuntime(29256): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
10-10 16:17:00.269: E/AndroidRuntime(29256): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
10-10 16:17:00.269: E/AndroidRuntime(29256): at dalvik.system.NativeStart.main(Native Method)
My Code:
public class Custom_CameraActivity extends Activity implements OnClickListener, Callback {
private static Camera camera;
private static int vesion;
private static int which;
private int brightness;
private Bitmap cameraBitmap;
private ImageView capt_btn;
int currBrightness;
private ImageView flash_btn;
private VerticalSeekBar greenSeekbar;
#SuppressLint({"HandlerLeak"})
Handler handler;
private boolean hasFlash;
private boolean isLighOn;
private ImageView list_btn;
private PictureCallback mPicture;
private int max_zoom_factor;
private boolean previewing;
private int screenHeight;
private int screenWidth;
private Bitmap surfaceBitmap;
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
private ImageView turn_btn;
private SeekBar zoomSeekBar;
private int zoom_factor;
public Custom_CameraActivity() {
this.previewing = false;
this.isLighOn = false;
this.zoom_factor = 0;
this.max_zoom_factor = 0;
this.handler = new Handler(){
public void handleMessage(Message msg) {
if (msg.what == 0) {
Toast.makeText(Custom_CameraActivity.this, Custom_CameraActivity.this.getResources().getString(R.string.txt_toastPhotoNotSaved), 0).show();
} else {
Toast.makeText(Custom_CameraActivity.this, Custom_CameraActivity.this.getResources().getString(R.string.txt_toastPhotoSaved), 0).show();
}
Custom_CameraActivity.this.surfaceView.setBackgroundColor(Color.argb(100, 0, MotionEventCompat.ACTION_MASK, 0));
}
};
this.mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Custom_CameraActivity.this.cameraBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Custom_CameraActivity.this.cameraBitmap = Custom_CameraActivity.getResizedBitmap(Custom_CameraActivity.this.cameraBitmap, Custom_CameraActivity.this.screenHeight, Custom_CameraActivity.this.screenWidth);
Custom_CameraActivity.this.joinBitmap();
camera.startPreview();
}
};
}
static {
camera = null;
which = 0;
vesion = 0;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
requestWindowFeature(1);
window.setFlags(AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT, AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT);
setContentView(R.layout.activity_main);
bindView();
init();
addListener();
}
protected void onResume() {
super.onResume();
}
private void bindView() {
this.surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
this.flash_btn = (ImageView) findViewById(R.id.flash);
this.capt_btn = (ImageView) findViewById(R.id.capture);
this.turn_btn = (ImageView) findViewById(R.id.turn);
this.zoomSeekBar = (SeekBar) findViewById(R.id.zoom_seekbar);
this.greenSeekbar = (VerticalSeekBar) findViewById(R.id.sbGreen);
this.list_btn = (ImageView) findViewById(R.id.list);
}
private void init() {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
this.screenHeight = metrics.heightPixels;
this.screenWidth = metrics.widthPixels;
this.surfaceHolder = this.surfaceView.getHolder();
this.surfaceHolder.addCallback(this);
this.surfaceHolder.setType(3);
try {
this.brightness = System.getInt(getContentResolver(), "screen_brightness");
this.currBrightness = this.brightness;
} catch (Exception e) {
Log.m0d("TAG", "Cannot access system brightness");
e.printStackTrace();
}
this.greenSeekbar.setMax(220);
this.greenSeekbar.setProgress(100);
this.surfaceView.setBackgroundColor(Color.argb(100, 0, MotionEventCompat.ACTION_MASK, 0));
}
private void addListener() {
this.flash_btn.setOnClickListener(this);
this.capt_btn.setOnClickListener(this);
this.turn_btn.setOnClickListener(this);
this.list_btn.setOnClickListener(this);
this.zoomSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
Custom_CameraActivity.this.zoomTo(progress, false);
}
});
this.greenSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
Custom_CameraActivity.this.surfaceView.setBackgroundColor(Color.argb(progress, 0, MotionEventCompat.ACTION_MASK, 0));
}
});
}
private void screenBrightness(double newBrightnessValue) {
LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = ((float) newBrightnessValue) / 255.0f;
getWindow().setAttributes(lp);
}
#SuppressWarnings("deprecation")
public void onClick(View v) {
switch (v.getId()) {
case R.id.turn:
turn();
case R.id.capture:
camera.takePicture(null, null, this.mPicture);
case R.id.flash:
this.hasFlash = getApplicationContext().getPackageManager().hasSystemFeature("android.hardware.camera.flash");
if (this.hasFlash) {
Parameters p = camera.getParameters();
if (this.isLighOn) {
p.setFlashMode("off");
camera.setParameters(p);
flash_btn.setBackgroundResource(R.drawable.ic_off);
camera.stopPreview();
camera.startPreview();
this.isLighOn = false;
return;
}
p.setFlashMode("torch");
camera.setParameters(p);
flash_btn.setBackgroundResource(R.drawable.ic_on);
camera.startPreview();
this.isLighOn = true;
return;
}
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle(getResources().getString(R.string.txt_dialogFlashTitle));
alert.setMessage(getResources().getString(R.string.txt_dialogFlashMsg));
alert.setButton(getResources().getString(R.string.txt_dialogFlashBtnOk), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.show();
case R.id.list:
startActivity(new Intent(this, MySavedPics.class));
default:
}
}
void setCameraDisplayOrientation(Activity activity, int cameraId, Camera camera) {
if (camera != null) {
int result;
CameraInfo info = new CameraInfo();
int degrees = 0;
switch (activity.getWindowManager().getDefaultDisplay().getRotation()) {
case 0:
degrees = 0;
break;
case 1:
degrees = 90;
break;
case 2:
degrees = 180;
break;
case 3:
degrees = 270;
break;
}
if (info.facing == 1) {
result = (360 - ((info.orientation + degrees) % 360)) % 360;
} else {
result = ((info.orientation - degrees) + 360) % 360;
}
camera.setDisplayOrientation(result);
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (this.previewing) {
camera.stopPreview();
this.previewing = false;
}
Parameters parameters = camera.getParameters();
if (camera != null) {
try {
camera.setPreviewDisplay(this.surfaceHolder);
camera.startPreview();
this.previewing = true;
if (parameters.isZoomSupported()) {
this.max_zoom_factor = parameters.getMaxZoom();
this.zoomSeekBar.setMax(this.max_zoom_factor);
this.zoomSeekBar.setProgress(this.zoom_factor);
this.zoomSeekBar.setVisibility(0);
return;
}
this.zoomSeekBar.setVisibility(8);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
try {
if (vesion == 1) {
Camera.open(which);
} else {
camera = Camera.open();
}
} catch (Exception e) {
camera.release();
}
try {
Parameters parameters = camera.getParameters();
if (getResources().getConfiguration().orientation != 2) {
parameters.set("orientation", "portrait");
camera.setDisplayOrientation(90);
parameters.setRotation(90);
} else {
parameters.set("orientation", "landscape");
camera.setDisplayOrientation(0);
parameters.setRotation(0);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(this.surfaceHolder);
} catch (IOException e2) {
camera.release();
}
camera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder arg0) {
camera.stopPreview();
camera.release();
camera = null;
vesion = 0;
this.previewing = false;
}
public void zoomTo(int new_zoom_factor, boolean update_seek_bar) {
Log.m0d("TAG", "ZoomTo(): " + new_zoom_factor);
if (new_zoom_factor < 0) {
new_zoom_factor = 0;
}
if (new_zoom_factor > this.max_zoom_factor) {
new_zoom_factor = this.max_zoom_factor;
}
if (new_zoom_factor != this.zoom_factor && camera != null) {
Parameters parameters = camera.getParameters();
if (parameters.isZoomSupported()) {
Log.m0d("TAG", "zoom was: " + parameters.getZoom());
parameters.setZoom(new_zoom_factor);
try {
camera.setParameters(parameters);
this.zoom_factor = new_zoom_factor;
if (update_seek_bar) {
this.zoomSeekBar.setProgress(this.max_zoom_factor - this.zoom_factor);
}
} catch (RuntimeException e) {
e.printStackTrace();
}
}
}
}
public void turn() {
if (VERSION.SDK_INT <= 9) {
AlertDialog.Builder ab1 = new AlertDialog.Builder(this);
ab1.setTitle(getResources().getString(R.string.txt_dialogTurnTitlesec));
ab1.setMessage(getResources().getString(R.string.txt_dialogTurnMsgsec));
ab1.setCancelable(false);
ab1.setPositiveButton(getResources().getString(R.string.txt_dialogTurnBtnOksec), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
//9967559972
} else if (Camera.getNumberOfCameras() >= 2) {
vesion = 1;
camera.stopPreview();
camera.release();
switch (which) {
case 0:
camera = Camera.open(1);
this.flash_btn.setEnabled(false);
camera.setDisplayOrientation(90);
which = 1;
break;
case 1:
camera = Camera.open(0);
this.flash_btn.setEnabled(true);
camera.setDisplayOrientation(90);
which = 0;
break;
}
try {
camera.setPreviewDisplay(this.surfaceHolder);
camera.setPreviewCallback(null);
camera.startPreview();
} catch (IOException e) {
camera.release();
camera = null;
}
} else {
vesion = 0;
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setTitle(getResources().getString(R.string.txt_dialogTurnTitle));
ab.setMessage(getResources().getString(R.string.txt_dialogTurnMsg));
ab.setCancelable(false);
ab.setPositiveButton(getResources().getString(R.string.txt_dialogTurnBtnOk), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
public void joinBitmap() {
this.surfaceView.setBackgroundColor(-16711936);
this.surfaceView.setDrawingCacheEnabled(true);
this.surfaceView.buildDrawingCache();
this.surfaceView.refreshDrawableState();
new Thread() {
public void run() {
try {
Custom_CameraActivity.this.surfaceBitmap = Custom_CameraActivity.this.surfaceView.getDrawingCache();
if (Custom_CameraActivity.this.surfaceBitmap != null) {
File pictureFile = Custom_CameraActivity.getOutputMediaFile();
if (pictureFile != null) {
Bitmap finalbitmap = Custom_CameraActivity.overlay(Custom_CameraActivity.this.cameraBitmap, Custom_CameraActivity.this.surfaceBitmap, Custom_CameraActivity.this.greenSeekbar.getProgress() + 15);
if (pictureFile.exists()) {
pictureFile.delete();
}
try {
FileOutputStream out = new FileOutputStream(pictureFile);
finalbitmap.compress(CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
} catch (IOException e2) {
}
Custom_CameraActivity.this.handler.sendEmptyMessage(1);
return;
}
return;
}
Custom_CameraActivity.this.handler.sendEmptyMessage(0);
} catch (Exception e3) {
}
}
}.start();
}
public static Bitmap getResizedBitmap(Bitmap bitmap, int newHeight, int newWidth) {
Bitmap dest = null;
try {
int sourceWidth = bitmap.getWidth();
int sourceHeight = bitmap.getHeight();
float scale = Math.min(((float) sourceWidth) / ((float) newWidth), ((float) sourceHeight) / ((float) newHeight));
float scaledWidth = ((float) sourceWidth/ scale);
float scaledHeight = ((float) sourceHeight/ scale);
dest = Bitmap.createBitmap(Bitmap.createScaledBitmap(bitmap, (int) scaledWidth, (int) scaledHeight, true), (int) ((scaledWidth - ((float) newWidth)) / 2.0f), (int) ((scaledHeight - ((float) newHeight)) / 2.0f), newWidth, newHeight);
} catch (Exception e) {
}
return dest;
}
public static Bitmap overlay(Bitmap bitmap1, Bitmap bitmapOverlay, int opacity) {
Bitmap resultBitmap = Bitmap.createBitmap(bitmapOverlay.getWidth(), bitmapOverlay.getHeight(), Config.ARGB_8888);
Canvas c = new Canvas(resultBitmap);
c.drawBitmap(bitmap1, 0.0f, 0.0f, null);
Paint p = new Paint();
p.setAlpha(opacity);
c.drawBitmap(bitmapOverlay, 0.0f, 0.0f, p);
return resultBitmap;
}
#SuppressLint({"SimpleDateFormat"})
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "Night Vision Camera");
if (mediaStorageDir.exists() || mediaStorageDir.mkdirs()) {
return new File(mediaStorageDir.getPath() + File.separator + "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpg");
}
Log.m0d("Night Vision Camera", "failed to create directory");
return null;
}
}
Related
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.
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);
}
}
I am developing one application in that i want to show camera surfaceview with back and front camera. In that switch camera is working but capture image then it will raise method called after release exception. How can i solve this please can anyone tell me .....
logcat:
10-09 10:32:33.530: E/AndroidRuntime(8915): FATAL EXCEPTION: main
10-09 10:32:33.530: E/AndroidRuntime(8915): java.lang.RuntimeException: Method called after release()
10-09 10:32:33.530: E/AndroidRuntime(8915): at android.hardware.Camera.native_takePicture(Native Method)
10-09 10:32:33.530: E/AndroidRuntime(8915): at android.hardware.Camera.takePicture(Camera.java:1095)
10-09 10:32:33.530: E/AndroidRuntime(8915): at android.hardware.Camera.takePicture(Camera.java:1040)
10-09 10:32:33.530: E/AndroidRuntime(8915): at com.example.cameraview.CamTestActivity$4.onClick(CamTestActivity.java:124)
10-09 10:32:33.530: E/AndroidRuntime(8915): at android.view.View.performClick(View.java:4207)
10-09 10:32:33.530: E/AndroidRuntime(8915): at android.view.View$PerformClick.run(View.java:17372)
10-09 10:32:33.530: E/AndroidRuntime(8915): at android.os.Handler.handleCallback(Handler.java:725)
10-09 10:32:33.530: E/AndroidRuntime(8915): at android.os.Handler.dispatchMessage(Handler.java:92)
10-09 10:32:33.530: E/AndroidRuntime(8915): at android.os.Looper.loop(Looper.java:137)
10-09 10:32:33.530: E/AndroidRuntime(8915): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-09 10:32:33.530: E/AndroidRuntime(8915): at java.lang.reflect.Method.invokeNative(Native Method)
10-09 10:32:33.530: E/AndroidRuntime(8915): at java.lang.reflect.Method.invoke(Method.java:511)
10-09 10:32:33.530: E/AndroidRuntime(8915): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-09 10:32:33.530: E/AndroidRuntime(8915): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-09 10:32:33.530: E/AndroidRuntime(8915): at dalvik.system.NativeStart.main(Native Method)
camera.java:
public class CamTestActivity extends Activity implements CameraCallback {
private static final String TAG = "CamTestActivity";
Preview preview;
Button buttonClick,front,zoomin,zoomout,tattooselect;
Camera camera;
Activity act;
Context ctx;
ImageView imm,aboveimg;
LayoutInflater controlInflater ;
Camera.Parameters params;
public RelativeLayout layout,rlayout;
Bitmap bitmap=null;
SurfaceHolder surfaceholder;
int myScreenHeight = 0;
int myScreenWidth = 0;
Bitmap bitmapPicture;
#SuppressLint("InlinedApi")
boolean previewing = false;
#SuppressLint("InlinedApi")
public static int camId = Camera.CameraInfo.CAMERA_FACING_BACK;
int numberOfCamera;
private int[] tattoos;
GridView gview;
Bitmap backimage;
public static File outFile;
int screenWidth, screenHeight;
public static String fileName;
int position;
int cameraID;
boolean isFrontCamera=false;
View v;
#SuppressLint({ "NewApi", "ShowToast" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this;
act = this;
setContentView(R.layout.main);
layout=(RelativeLayout)findViewById(R.id.relative);
rlayout=(RelativeLayout)findViewById(R.id.rrlayout);
preview = new Preview(this, (SurfaceView)findViewById(R.id.surfaceView));
preview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
imm=(ImageView)findViewById(R.id.imageView1);
aboveimg=(ImageView)findViewById(R.id.imageView2);
rlayout.addView(preview);
aboveimg.setOnTouchListener(new Touchhimage());
Toast.makeText(getApplicationContext(), "" +camId,Toast.LENGTH_LONG).show();
preview.setKeepScreenOn(true);
buttonClick = (Button)findViewById(R.id.btnCapture);
//buttonClick.setPressed(true);
zoomin=(Button)findViewById(R.id.button3);
zoomout=(Button)findViewById(R.id.button2);
front=(Button)findViewById(R.id.button1);
gview=(GridView)findViewById(R.id.gridview);
tattooselect=(Button)findViewById(R.id.button4);
//setCameraDisplayOrientation(CamTestActivity.this, currentCameraId, camera);
buttonClick.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
zoomin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
preview.zoom();
}
});
zoomout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
preview.unzoom();
}
});
if(Camera.getNumberOfCameras() == 1){
front.setVisibility(View.INVISIBLE);
}
else {
front.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
preview.openFrontFacingCamera();
}
});
}
tattooselect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
gview.setAdapter(new GridAdapter(getApplicationContext()));
gview.setVisibility(View.VISIBLE);
}
});
gview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "visible", 1000).show();
backimage= BitmapFactory.decodeResource(getResources(), tattoos[position]);
scaling(backimage);
aboveimg.setVisibility(View.VISIBLE);
aboveimg.setImageBitmap(Utils.camerabitmap);
gview.setVisibility(View.INVISIBLE);
}
});
}
public void scaling(Bitmap backimage)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// BitmapFactory.decodeStream(in, null, options);
/// in.close();
// in = null;
// save width and height
// inWidth = options.outWidth;
// inHeight = options.outHeight;
// decode full image pre-resized
// in = new FileInputStream(imageFile.getAbsolutePath());
options = new BitmapFactory.Options();
// calc rought re-size (this is no exact resize)
//options.inSampleSize = Math.max(inWidth/screenWidth, inHeight/screenHeight);
// decode full image
// Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);
// calc exact destination size
Matrix m = new Matrix();
RectF inRect = new RectF(0, 0, backimage.getWidth(), backimage.getHeight());
RectF outRect = new RectF(0, 0, screenWidth, screenHeight);
m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
float[] values = new float[9];
m.getValues(values);
// resize bitmap
Utils.camerabitmap = Bitmap.createScaledBitmap(backimage, imm.getWidth(), imm.getHeight(), true);
}
#SuppressLint("NewApi") #Override
protected void onResume() {
super.onResume();
//camera.setPreviewCallback(null);
camera = Camera.open(camId);
// camera.startPreview();
preview.setCamera(camera);
}
#Override
protected void onPause() {
if(camera != null) {
//camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera=null;
}
super.onPause();
}
/*public void initializecamera()
{
preview = new Preview(this, (SurfaceView)findViewById(R.id.surfaceView));
preview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
rlayout.addView(preview);
buttonClick.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
}*/
#SuppressLint("NewApi")
private void resetCam() {
imm.setVisibility(View.INVISIBLE);
camera.startPreview();
preview.setCamera(camera);
}
private void refreshGallery(File file) {
Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(file));
sendBroadcast(mediaScanIntent);
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
//Log.d(TAG, "onShutter'd");
}
};
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//Log.d(TAG, "onPictureTaken - raw");
}
};
PictureCallback jpegCallback = new PictureCallback() {
#SuppressLint({ "NewApi", "DefaultLocale" })
public void onPictureTaken(byte[] data, Camera camera) {
//dataaa=data;
// new SaveImageTask().execute(data);
bitmapPicture = BitmapFactory.decodeByteArray(data, 0, data.length);
//setCameraDisplayOrientation(CamTestActivity.this, camId, camera);
imm.setImageBitmap(bitmapPicture);
imm.setVisibility(View.VISIBLE);
//resetCam();
FileOutputStream outStream = null;
layout.getRootView();
layout.setDrawingCacheEnabled(true);
layout.buildDrawingCache();
Bitmap m=layout.getDrawingCache();
// Write to SD Card
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
fileName = String.format("%d.jpg", System.currentTimeMillis());
outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
m.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
outStream.write(data[0]);
outStream.flush();
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
refreshGallery(outFile);
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
}
Intent i=new Intent(CamTestActivity.this,Imageshare.class);
i.putExtra("imagepath", outFile.getAbsolutePath());
startActivity(i);
resetCam();
Log.d(TAG, "onPictureTaken - jpeg");
}
};
surfaceview.java:
class Preview extends ViewGroup implements SurfaceHolder.Callback {
protected static final String camera = null;
Camera.Parameters params;
private final String TAG = "Preview";
protected Camera.Size mPictureSize;
protected Activity mActivity;
SurfaceView mSurfaceView;
SurfaceHolder mHolder;
Size mPreviewSize;
List<Size> mSupportedPreviewSizes;
Camera mCamera;
Context context;
int currentZoomLevel ;
int maxZoomLevel ;
boolean previewing = false;
#SuppressLint("InlinedApi")
int camId;
int noofcameras;
public static CameraInfo info;
// private CameraCallback callback = null;
List<Camera.Size> previewSizes;
private CameraCallback callback = null;
int cameraID;
public boolean cameraConfigured=false;
private static final int PICTURE_SIZE_MAX_WIDTH = 1280;
private static final int PREVIEW_SIZE_MAX_WIDTH = 640;
//private TutorialThread _thread;
#SuppressLint("NewApi")
#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);
//params = mCamera.getParameters();
}
public void setCamera(Camera camera) {
mCamera = camera;
if (mCamera != null) {
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
requestLayout();
// get 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 = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
}
}
#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);
}
}
}
#SuppressLint({ "WrongCall", "NewApi" })
public void surfaceCreated(final SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
/*
determineDisplayOrientation();
setupCamera();*/
/*try {
if (mCamera != null) {
// mCamera = Camera.open(camId);
mCamera.setPreviewDisplay(holder);
//mCamera.startPreview();
//mCamera=Camera.open(camId);
params = mCamera.getParameters();
params.set("orientation", "portrait");
params.setRotation(90);
mCamera.setDisplayOrientation(90);
mCamera.setParameters(params);
mCamera.startPreview();
}
} catch (IOException exception) {
Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
}*/
camId=findCameraID();
noofcameras = Camera.getNumberOfCameras();
info = new CameraInfo();
Camera.getCameraInfo(camId, info);
if(mCamera==null){
mCamera = Camera.open(camId);
//safeCameraOpen(camId);
}
// camera = Camera.open();
try {
mCamera.setPreviewDisplay(holder);
mCamera.setPreviewCallback(new Camera.PreviewCallback() {
#Override
public void onPreviewFrame(byte[] data, Camera camera) {
if(null != callback) callback.onPreviewFrame(data, camera);
}
});
params = mCamera.getParameters();
params.set("orientation", "portrait");
params.setRotation(90);
mCamera.setDisplayOrientation(90);
mCamera.setParameters(params);
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressLint({ "NewApi", "ShowToast" })
public void openFrontFacingCamera() {
noofcameras = Camera.getNumberOfCameras();
if(camId == Camera.CameraInfo.CAMERA_FACING_BACK){
camId = Camera.CameraInfo.CAMERA_FACING_FRONT;
try {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera=null;
mCamera = Camera.open(camId);
//onOrientationChanged(0);
mCamera.setPreviewDisplay(mHolder);
mCamera.setPreviewCallback(new Camera.PreviewCallback() {
#Override
public void onPreviewFrame(byte[] data, Camera camera) {
if(null != callback) callback.onPreviewFrame(data, camera);
}
});
mCamera.setDisplayOrientation(90);
mCamera.startPreview();
//previewing = true;
} catch (RuntimeException e) {
}catch (IOException e) {}
}else if(camId == Camera.CameraInfo.CAMERA_FACING_FRONT){
camId = Camera.CameraInfo.CAMERA_FACING_BACK;
try {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera=null;
mCamera=Camera.open(camId);
mCamera.setPreviewDisplay(mHolder);
mCamera.setPreviewCallback(new Camera.PreviewCallback() {
#Override
public void onPreviewFrame(byte[] data, Camera camera) {
if(null != callback) callback.onPreviewFrame(data, camera);
}
});
mCamera.setDisplayOrientation(90);
mCamera.startPreview();
} catch (RuntimeException e) {
}catch (IOException e) {}
}
}
#SuppressLint("NewApi")
private int findCameraID() {
// TODO Auto-generated method stub
int foundId = -1;
int numCams = Camera.getNumberOfCameras();
System.out.println("no of cameras are "+numCams);
for (int camId = 0; camId < numCams; camId++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(camId, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
foundId = camId;
break;
}else
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
foundId = camId;
break;
}
}
return foundId;
}
public void zoom()
{
params=mCamera.getParameters();
maxZoomLevel = params.getMaxZoom();
if (currentZoomLevel < maxZoomLevel) {
currentZoomLevel++;
params.setZoom(currentZoomLevel);
mCamera.setParameters(params);
}
}
public void unzoom()
{
params=mCamera.getParameters();
maxZoomLevel = params.getMaxZoom();
if (currentZoomLevel > 0) {
currentZoomLevel--;
params.setZoom(currentZoomLevel);
mCamera.setParameters(params);
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
if (mCamera != null) {
//mCamera.stopPreview();
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
previewing = false;
}
}
private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
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 void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if(mCamera != null) {
params=mCamera.getParameters();
params.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
mCamera.setParameters(params);
requestLayout();
mCamera.setDisplayOrientation(90);
mCamera.startPreview();
}
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);
}
}
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.