I am trying to record a video in background through Service but my code creates and empty video file everytime and not returning any error as well.
Below is my Service class:
public class BackGroundVideoRecorder extends Service implements SurfaceHolder.Callback {
private static final String LOG_TAG = "BackGroundVideoRecorder";
private MediaRecorder mediaRecorder = null;
private WindowManager windowManager;
private SurfaceView surfaceView;
private Camera camera = null;
#Override
public void onCreate() {
// Create new SurfaceView, set its size to 1x1, move it to the top left corner and set this service as a callback
windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
surfaceView = new SurfaceView(this);
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
1, 1,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT
);
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
windowManager.addView(surfaceView, layoutParams);
surfaceView.getHolder().addCallback(this);
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
camera = Camera.open(1);
mediaRecorder = new MediaRecorder();
camera.unlock();
//mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.setCamera(camera);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setVideoSize(320, 480);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
String out = Environment.getExternalStorageDirectory() + "/Output/" +
DateFormat.format("yyyy-MM-dd_kk-mm-ss", new Date().getTime()) +
".mp4";
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "Output");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("FolderName", "failed to create directory");
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_" + timeStamp + ".mp4");
mediaRecorder.setMaxDuration(30000);
mediaRecorder.setOutputFile(mediaFile);
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
try {
mediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaRecorder.start();
}
// Stop recording and remove SurfaceView
#Override
public void onDestroy() {
if (camera != null) {
camera.lock();
camera.release();
}
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.reset();
mediaRecorder.release();
}
if (windowManager != null) {
windowManager.removeView(surfaceView);
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Please suggest any solution or error if you found.
Thanks in advance.
Related
Here is the code which i am using to capture image, but now my question is How Do I Compress Size of Image taken by my Custom Camera
CameraSurfaceView.java:
class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
Camera camera;
CameraSurfaceView(Context context) {
super(context);
SurfaceHolder holder = this.getHolder();
holder.addCallback(this);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
camera.setDisplayOrientation(90);
camera.startPreview();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
// Open the Camera in preview mode
this.camera = Camera.open();
this.camera.setPreviewDisplay(holder);
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
}
public void takePicture(PictureCallback imageCallback) {
Camera.Parameters params = camera.getParameters();
params.setRotation(90);
camera.setParameters(params);
camera.takePicture(null, null, imageCallback);
}
}
Here is the Class which I am using to Capture Image
CameraCaptureActivity.java:
CameraSurfaceView cameraSurfaceView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_capture);
// set up our preview surface
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
cameraSurfaceView = new CameraSurfaceView(this);
preview.addView(cameraSurfaceView);
// grab out shutter button so we can reference it later
shutterButton = (Button) findViewById(R.id.btnCapture);
shutterButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
takePicture();
}
private void takePicture() {
shutterButton.setEnabled(false);
cameraSurfaceView.takePicture(this);
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO something with the image data
File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
return;
}
simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
strDateFormat = simpleDateFormat.format(new Date());
String photoFile = strRecordName+strDateFormat+".jpg";
String filename = pictureFileDir.getPath() + File.separator + photoFile;
File pictureFile = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast.makeText(CameraCaptureActivity.this, "Image saved:" + photoFile,
Toast.LENGTH_LONG).show();
// Restart the preview and re-enable the shutter button so that we can take another picture
camera.stopPreview();
shutterButton.setEnabled(false);
} catch (Exception error) {
Toast.makeText(CameraCaptureActivity.this, "Image could not be saved.",
Toast.LENGTH_LONG).show();
}
}
private File getDir() {
File sdDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "CustomCamera");
}
public void onResume()
{
super.onResume();
shutterButton.setEnabled(true);
}
Do like
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap pic = BitmapFactory.decodeByteArray(data, 0, data.length);
//Rotate the image by 90 degrees before we save it
Matrix matrix = new Matrix();
matrix.postRotate(90);
pic = Bitmap.createBitmap(pic , 0, 0, pic.getWidth(), pic.getHeight(), matrix, true);
........
FileOutputStream fos = new FileOutputStream(pictureFile);
pic.compress(Bitmap.CompressFormat.PNG, 90, fOut);
}
I am making my own camera in android, then whenever I capture images the images orientation is okay. but when i open it in my external sdcard file it is like that:
this is my code:
public class CameraApp extends Activity implements SurfaceHolder.Callback {
private static final String TAG = "IMG_";
private static final String IMAGE_FOLDER = "/PhoneController/";
private static final String EXTENTION = ".jpg";
private String pictureName = "";
public String picNameToshare = "";
static final int FOTO_MODE = 0;
String speed;
String imageFilePath;
private Handler mHandler = new Handler();
public static String imageFilePath1;
FileOutputStream fos = null;
public Bitmap framebmpScaled;
public Bitmap SelecedFrmae;
public static Bitmap mergeBitmap;
public static Bitmap bmpfULL;
Camera camera;
Button button;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.camera);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(buttonListener);
}
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
Handler myHandler = new Handler();
if (previewing) {
camera.stopPreview();
previewing = false;
Log.e("", "one");
}
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
myHandler.postDelayed(mMyRunnable, 2000); // called after 5
// seconds
button.setText("Waiting...");
Log.e("", "two");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* Handler myHandler = new Handler();
* myHandler.postDelayed(mMyRunnable, 5000); // called after 5
* seconds button.setText("Waiting...");
*/
}
};
private Runnable mMyRunnable = new Runnable() {
public void run() {
Camera.Parameters params = camera.getParameters();
params.set("rotation", 90);
camera.setParameters(params);
camera.takePicture(myShutterCallback, myPictureCallback_RAW,
myPictureCallback_JPG);
storePicture(mergeBitmap);
button.setText("Capture");
}
};
PictureCallback myPictureCallback_JPG = new PictureCallback() {
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
Display display = getWindowManager().getDefaultDisplay();
final int ScreenWidth = display.getWidth();
final int ScreenHeight = display.getHeight();
Log.e("" + display.getWidth(), "" + display.getWidth());
Bitmap bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0,
arg0.length);
Bitmap bmpScaled1 = Bitmap.createScaledBitmap(bitmapPicture,
ScreenWidth, ScreenHeight, true);
mergeBitmap = bmpScaled1;
showPicture();
}
};
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);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
camera.setDisplayOrientation(90);
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
void storePicture(Bitmap bm) {
mHandler.post(new Runnable() {
public void run() {
// showPicture();
}
});
String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss")
.format(new Date());
this.pictureName = TAG + timeStamp;
picNameToshare = this.pictureName;
this.imageFilePath = IMAGE_FOLDER + this.pictureName + EXTENTION;
this.imageFilePath = sanitizePath(this.imageFilePath);
try {
checkSDCard(this.imageFilePath);
fos = new FileOutputStream(this.imageFilePath);
if (fos != null) {
bm.compress(Bitmap.CompressFormat.JPEG, 85, fos);
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
fos.close();
}
} catch (IOException ioe) {
Log.e(TAG, "CapturePicture : " + ioe.toString());
} catch (Exception e) {
Log.e(TAG, "CapturePicture : " + e.toString());
}
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
imageFilePath1 = this.imageFilePath;
}
/**
* Check the SDCard is mounted on device
*
* #param path
* of image file
* #throws IOException
*/
void checkSDCard(String path) throws IOException {
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
Toast.makeText(this,
"Please insert sdcard other wise image won't stored",
Toast.LENGTH_SHORT).show();
throw new IOException("SD Card is not mounted. It is " + state
+ ".");
}
// make sure the directory we plan to store the recording is exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
}
private String sanitizePath(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ path;
}
please help me.
Try using this
Camera.Parameters parameters = camera.getParameters();
parameters.set("orientation", "portrait");
camera.setParameters(parameters);
Below is the code for a custom camera app I'm working on. Everthing works fine, except when the images are taken with flash on. With flash on, the preview showed to the user to accept the image looks right, but the image saved to the sdcard is very dark (with only white objects slightly visible) and often just black. I've been trying to figure out the problem for days now. Any ideas what might be going on?
public class CustomCamera extends Activity implements SurfaceHolder.Callback{
Camera camera;
Surfaceview surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
#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);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
...
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
Camera.Parameters parameters = camera.getParameters();
camera.setDisplayOrientation(90);
determineDisplayOrientation();
camera.setPreviewDisplay(surfaceHolder);
previewing = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
List<String> supportedFocusModes = parameters.getSupportedFocusModes();
if (supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)){
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
} else{
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
}
}
if (parameters.getSupportedWhiteBalance().contains(
Parameters.WHITE_BALANCE_AUTO)) {
parameters.setWhiteBalance(Parameters.WHITE_BALANCE_AUTO);
}
if (parameters.getSupportedSceneModes().contains(
Parameters.SCENE_MODE_AUTO)) {
parameters.setSceneMode(Parameters.SCENE_MODE_AUTO);
}
camera.setParameters(parameters);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
flashButton.setBackgroundResource(R.drawable.auto_flash);
camera = Camera.open(CURRENT_CAMERA_ID);
Camera.Parameters camParameters = camera.getParameters();
flashSupported = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if ( flashSupported){
camParameters.setFlashMode(Parameters.FLASH_MODE_AUTO);
lastFlashMode = AUTO_FLASH;
camera.setParameters(camParameters);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
//click listener for button to take picture
public void takePicture(View view){
if (camera != null){
orientationListener.rememberOrientation();
camera.takePicture(myShutterCallback, myPictureCallback_RAW, myPictureCallback_JPG);
showPicPreviewScreen();
}
}
Camera.ShutterCallback myShutterCallback = new Camera.ShutterCallback() {
#Override
public void onShutter() {
}
};
Camera.PictureCallback myPictureCallback_RAW = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
}
};
Camera.PictureCallback myPictureCallback_JPG = new Camera.PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
int rotation = (displayOrientation + orientationListener.getRememberedOrientation() + layoutOrientation) % 360;
if (rotation != 0){
Log.e("rotaion", "not 0, rotating");
Bitmap oldBitmap = bitmapPicture;
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
bitmapPicture = Bitmap.createBitmap(bitmapPicture, 0, 0, bitmapPicture.getWidth(), bitmapPicture.getHeight(), matrix, false);
oldBitmap.recycle();
}
camera.stopPreview();
previewing = false;
ImageSaver imageSaver = new ImageSaver();
imageSaver.saveImage(getApplicationContext(), bitmapPicture);
}
};
}
And here's the class that saves the image
public class ImageSaver{
private Context context;
private String NameOfFolder = "/ProjectFolder";
String fileName;
String file_path;
public void saveImage(Context context,Bitmap ImageToSave){
context = context;
file_path = Environment.getExternalStorageDirectory().getAbsolutePath()+ NameOfFolder;
String CurrentDateAndTime= getCurrentDateAndTime();
File dir = new File(file_path);
if(!dir.exists()){
dir.mkdirs();
}
fileName = CurrentDateAndTime+ ".jpg";
File file = new File(dir, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
ImageToSave.compress(Bitmap.CompressFormat.JPEG, 100, fOut); //85
fOut.flush();
fOut.close();
}
catch (FileNotFoundException e) {UnableToSave();}
catch (IOException e){UnableToSave();}
}
private String getCurrentDateAndTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String formattedDate = df.format(c.getTime());
return formattedDate;
}
}
Thanks a lot!
I've written a camera application, but when I want to show the camera's live preview(before taking the picture), the preview is rotated 90 degrees! here is my camera activity's code :
public class CameraActivity extends Activity{
public static final int MEDIA_TYPE_IMAGE = 1 ;
private Camera mCamera;
private CameraPreview mPreview;
Uri photoPath ;
protected void onStop()
{
super.onStop();
mCamera.release();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
ViewGroup.LayoutParams previewParam = preview.getLayoutParams() ;
Parameters cameraParam = mCamera.getParameters() ;
double ratio = (double)cameraParam.getPictureSize().height / (double)cameraParam.getPictureSize().width ;
// previewParam.height= cameraParam.getPictureSize().height / 5 ;
// previewParam.width = cameraParam.getPictureSize().width / 5 ;
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
try
{
display.getSize(size);
}
catch(java.lang.NoSuchMethodError ignore)
{
size.x = display.getWidth();
size.y = display.getHeight() ;
}
int width = size.x;
int height = size.y;
previewParam.width = width;
previewParam.height = (int)(previewParam.width * ratio) ;
// preview.setLayoutParams(previewParam) ;
preview.addView(mPreview);
}
//Camera Classes here
private final static String TAG = "Navid";
public static Camera getCameraInstance()
{
Camera c = null ;
try
{
c = Camera.open() ;
}
catch(Exception e)
{
}
return c ;
}
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback
{
private SurfaceHolder mHolder ;
private Camera mCamera;
public CameraPreview(Context context , Camera camera)
{
super(context) ;
mCamera = camera ;
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder)
{
try
{
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}
catch(IOException e)
{
Log.d(TAG,"Camera Preview Failed!: "+e.getMessage());
}
}
public void surfaceChanged(SurfaceHolder holder , int m , int n , int w)
{
}
public void surfaceDestroyed(SurfaceHolder holder)
{
}
}
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}else {
return null;
}
return mediaFile;
}
//save the picture here
private PictureCallback mPicture = new PictureCallback() {
// public final static int MEDIA_TYPE_IMAGE = 1 ;
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
photoPath = Uri.fromFile(pictureFile);
if (pictureFile == null){
Log.d("Errore Doorbin", "Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
// these lines are for the gallery to scan the SDCard manually
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+ mediaStorageDir)));
// photoPath = Uri.fromFile(mediaStorageDir) ;
/* MediaScannerConnection.scanFile(CameraActivity.this,
new String[] { fos.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
// code to execute when scanning is complete
}
});*/
// fos.close();
} catch (FileNotFoundException e) {
Log.d("Errore Doorbin", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Errore Doorbin", "Error accessing file: " + e.getMessage());
}
catch (Exception e)
{
Log.d("Errore Doorbin", "errore Kolli dade!" + e.getMessage()) ;
}
}
};
public void capture(View v)
{
//mCamera.takePicture(null, null, mPicture);
//mCamera.release();
//mCamera = getCameraInstance() ;
//mCamera.startPreview();
TakePictureTask takePicture = new TakePictureTask() ;
takePicture.execute() ;
}
public void accept(View v)
{
Intent data = new Intent() ;
data.setData(photoPath) ;
setResult(RESULT_OK, data);
finish() ;
}
public void retake(View v)
{
Button button = (Button)findViewById(R.id.button_accept);
button.setVisibility(View.GONE);
button = (Button)findViewById(R.id.button_capture) ;
button.setVisibility(View.VISIBLE) ;
button = (Button)findViewById(R.id.button_retake);
button.setVisibility(View.GONE) ;
mCamera.startPreview();
}
/**
* A pretty basic example of an AsyncTask that takes the photo and
* then sleeps for a defined period of time before finishing. Upon
* finishing, it will restart the preview - Camera.startPreview().
*/
private class TakePictureTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void result) {
// This returns the preview back to the live camera feed
Button button = (Button)findViewById(R.id.button_accept) ;
button.setVisibility(View.VISIBLE) ;
button = (Button)findViewById(R.id.button_retake) ;
button.setVisibility(View.VISIBLE);
button = (Button)findViewById(R.id.button_capture);
button.setVisibility(View.GONE);
//mCamera.startPreview();
}
#Override
protected Void doInBackground(Void... params) {
mCamera.takePicture(null, null, mPicture);
// Sleep for however long, you could store this in a variable and
// have it updated by a menu item which the user selects.
try {
Thread.sleep(3000); // 3 second preview
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
and in my application's manifest I've changed this activities orientation to portrait!
What is the problem ? why does it look like this ?
This happens to be a bug in earlier versions of Android.
A workaround is to rotate the camera by default.
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
camera.setDisplayOrientation(90);
lp.height = previewSurfaceHeight;
lp.width = (int) (previewSurfaceHeight / aspect);
} else {
camera.setDisplayOrientation(0);
lp.width = previewSurfaceWidth;
lp.height = (int) (previewSurfaceWidth / aspect);
}
I am able to place a overlay over a live camera feed, but I also need to save the image captured by camera with that overlay.
Here is the code of my MainActivity.class file :
public class MainActivity extends Activity {
private Button takePhoto, pickPhoto;
private FrameLayout preview;
private CameraSurfaceView cameraSurfaceView;
private static final int SELECT_PICTURE_ACTIVITY_RESULT_CODE = 1;
private static final int CAMERA_PIC_REQUEST = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePhoto = (Button) findViewById(R.id.btn_takephoto);
pickPhoto = (Button) findViewById(R.id.btn_pickPhoto);
preview = (FrameLayout) findViewById(R.id.frameLayout1);
takePhoto.setOnClickListener(clickListener);
pickPhoto.setOnClickListener(clickListener);
cameraSurfaceView = new CameraSurfaceView(MainActivity.this);
preview.addView(cameraSurfaceView);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.equals(takePhoto)) {
Camera camera = cameraSurfaceView.getCamera();
camera.takePicture(null, null, new HandlePictureStorage());
} else if (v.equals(pickPhoto)) {
Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*"); // to pick only images
photoPickerIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(photoPickerIntent,
SELECT_PICTURE_ACTIVITY_RESULT_CODE);
}
}
};
private class HandlePictureStorage implements PictureCallback {
#Override
public void onPictureTaken(byte[] picture, Camera camera) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "CameraTest" + date + ".jpg";
String filename = Environment.getExternalStorageDirectory()
+ File.separator + photoFile;
File pictureFile = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(picture);
fos.close();
Toast.makeText(getApplicationContext(),
"New Image saved:" + photoFile, Toast.LENGTH_LONG)
.show();
} catch (Exception error) {
Log.d("Error",
"File" + filename + "not saved: " + error.getMessage());
Toast.makeText(getApplicationContext(),
"Image could not be saved.", Toast.LENGTH_LONG).show();
}
Intent newInt = new Intent(MainActivity.this, AddImageOverlay.class);
newInt.putExtra(Constant.BitmatpByteArray, filename);
startActivity(newInt);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case SELECT_PICTURE_ACTIVITY_RESULT_CODE:
Uri selectedImageUri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(
this.getContentResolver(), selectedImageUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Photo Picked",
Toast.LENGTH_SHORT).show();
// deal with it
break;
default:
// deal with it
break;
}
}
}
}
And the code of CameraSurfaceView.java :
public class CameraSurfaceView extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder holder;
private Camera camera;
public CameraSurfaceView(Context context) {
super(context);
// Initiate the Surface Holder properly
this.holder = this.getHolder();
this.holder.addCallback(this);
this.holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder h, int format, int width,
int height) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(width, height);
camera.setParameters(parameters);
camera.startPreview();
h.getSurface().setLayer(R.drawable.ic_launcher);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
// Open the Camera in preview mode
this.camera = Camera.open();
this.camera.setPreviewDisplay(this.holder);
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when replaced with a new screen
// Always make sure to release the Camera instance
camera.stopPreview();
camera.release();
camera = null;
}
public Camera getCamera() {
return this.camera;
}
}