I need a help. I'm trying to implement Custom camera using surface vie, but I'm stacked into this error:
Process: visionary.anselmo.camerademo, PID: 7464
java.lang.RuntimeException: Fail to connect to camera service
at android.hardware.Camera.<init>(Camera.java:496)
at android.hardware.Camera.open(Camera.java:360)
at visionary.anselmo.camerademo.CameraActivity.surfaceCreated(CameraActivity.java:149)
at android.view.SurfaceView.updateWindow(SurfaceView.java:608)
at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:160)
at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:944)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2201)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1246)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6301)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
at android.view.Choreographer.doCallbacks(Choreographer.java:683)
at android.view.Choreographer.doFrame(Choreographer.java:619)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
And the here goes the activity that handles this:
public class CameraActivity extends AppCompatActivity implements SurfaceHolder.Callback {
#SuppressWarnings("deprecation")
private Camera camera;
#InjectView(R.id.surface_view)
SurfaceView surfaceView;
#InjectView(R.id.btn_take_picture)
ImageView take_picture;
SurfaceHolder surfaceHolder;
#SuppressWarnings("deprecation")
Camera.PictureCallback pictureCallback;
#SuppressWarnings("deprecation")
ShutterCallback shutterCallback;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_activity);
ButterKnife.inject(this);
surfaceHolder = surfaceView.getHolder();
// Install the surfaceHolder.Callback so we get notified when the underlying is created and destroyed
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
take_picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraImage();
}
});
pictureCallback = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outputStream;
File imageFile = getDirectory();
if (!imageFile.exists() && !imageFile.mkdirs()) {
Toast.makeText(getApplicationContext(),
"Nao foi possivel criar o directorio para a imagem.",
Toast.LENGTH_SHORT)
.show();
return;
}
SimpleDateFormat format = new SimpleDateFormat("yyyymmddhhmmss", Locale.ENGLISH);
String date = format.format(new Date());
String photoFile = "Demo" + date + ".jpg";
String fileName = imageFile.getAbsolutePath() + "/" + photoFile;
File picFile = new File(fileName);
try {
outputStream = new FileOutputStream(picFile);
outputStream.write(data);
outputStream.close();
} catch (IOException ignored) {
}
Toast.makeText(getApplicationContext(), "Picture Saved", Toast.LENGTH_SHORT)
.show();
refreshCamera();
refreshGallery(picFile);
}
};
}
private void refreshGallery(File file) {
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
}
private void refreshCamera() {
if (surfaceHolder.getSurface() == null) {
// Preview surfave does not exists
return;
}
// Stop the preview before making changes
try {
camera.stopPreview();
} catch (Exception ignored) {
}
// Set the preview size, and make any resize, rotate or any reformmating changes here
// Start preview with new Settings
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (Exception ignored) {
}
}
private File getDirectory() {
File dics = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
return new File(dics, "CameraActivity");
}
private void cameraImage() {
// Take the picture
camera.takePicture(null, null, pictureCallback);
}
#SuppressWarnings("deprecation")
#Override
public void surfaceCreated(SurfaceHolder holder) {
// Open the fuck'n Camera here
releaseCamera();
camera = Camera.open();
Camera.Parameters parameters;
parameters = camera.getParameters();
// Modify the parameters
parameters.setPreviewFrameRate(20);
parameters.setPreviewSize(352, 288);
camera.setParameters(parameters);
camera.setDisplayOrientation(90);
try {
// The surface has been created, now tell the camera where to draw the preview
camera.setPreviewDisplay(surfaceHolder);
} catch (Exception ignored) {
}
}
private void releaseCamera(){
if(camera != null){
camera.release();
camera = null;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
refreshCamera();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// Stop the preview and release the camera
camera.stopPreview();
camera.release();
camera = null;
}
}
Help guys...
Thanks...
You might need to request the permission at runtime. See The Android Developers Homepage for more information on this topic.
Requesting runtime permissions is required when targeting Android 6.0 or later.
Related
Im getting the exception java.lang.RuntimeException:Fail to connect to camera service when reopening the same activity.
For the first time the code works fine without capturing video file(only camera preview).But after finishing MainActivity.If I again calls Mainactivity then for mCamera = Camera.open(0); it throws Exception
I checked questions on stackoverflow but non of the solution worked for it.
Code
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, View.OnClickListener {
private VideoView videoView = null;
private MediaController mc = null;
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
public MediaRecorder mediaRecorder = new MediaRecorder();
private Camera mCamera;
private Button btnStart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(this);
if (mCamera == null) {
mCamera = Camera.open(0);
Camera.Parameters params = mCamera.getParameters();
mCamera.setParameters(params);
mCamera.setDisplayOrientation(90);
}
}
#SuppressLint("NewApi")
protected void startRecording() throws IOException {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/myVideos");
if (!dir.exists()) {
dir.mkdirs();
}
Date date = new Date();
String fileName = "/rec" + date.toString().replace(" ", "_").replace(":", "_") + ".mp4";
File file = new File(dir, fileName);
mediaRecorder = new MediaRecorder();
mCamera.lock();
mCamera.unlock();
mediaRecorder.setCamera(mCamera);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.setOutputFile(dir + fileName);
mediaRecorder.setOrientationHint(90);
mediaRecorder.prepare();
mediaRecorder.start();
refreshGallery(file);
}
private void refreshGallery(File file) {
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(file));
sendBroadcast(mediaScanIntent);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (mCamera != null) {
try {
if (mCamera != null) {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
mCamera.unlock();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Camera not available!",
Toast.LENGTH_LONG).show();
finish();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart:
if (btnStart.getText().toString().equalsIgnoreCase("Start")) {
btnStart.setText("Stop");
try {
startRecording();
} catch (IOException e) {
String message = e.getMessage();
Log.i(null, "Problem " + message);
mediaRecorder.release();
e.printStackTrace();
}
} else {
btnStart.setText("Start");
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
break;
default:
break;
}
}
#Override
public void onDestroy()
{
super.onDestroy();
if(mCamera!=null) {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
}
#Override
public void onBackPressed()
{
Intent intent=new Intent(MainActivity.this,FirstActivityActivity.class);
startActivity(intent);
super.onBackPressed();
}
}
can anyone tell me,whats wrong with the code?
here is the logcat
FATAL EXCEPTION: main
Process: com.example.surfaceviewrecord, PID: 11717
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.surfaceviewrecord/com.example.surfaceviewrecord.MainActivity}:
java.lang.RuntimeException: Fail to connect to camera service
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1494)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.RuntimeException: Fail to connect to camera service
at android.hardware.Camera.<init>(Camera.java:647)
at android.hardware.Camera.open(Camera.java:489)
at com.example.surfaceviewrecord.MainActivity.onCreate(MainActivity.java:47)
at android.app.Activity.performCreate(Activity.java:6582)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2532)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1494)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Permissions in manifest file
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
You need to apply Runtime Camera Permission from marshmallow and above. So here you haven't camera permission that's why this error occurred.
Please check this Link
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaRecorder();
if (camera != null) {
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
}
}
private void releaseMediaRecorder() {
if (mediaRecorder != null) {
mediaRecorder.release(); // release the recorder object
mediaRecorder = null;
}
}
Please check above code and put in at onDestroy() method.
I'm trying to capture an image from a SurfaceView custom camera. I have set up the initial code but I don't know how to call the 'take photo' method so that I can see the preview on the surface.
Currently this code displays the preview in realtime. I need to take the picture and access the byte[] array
Please help me complete the code:
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
captureImage = (ImageButton) findViewById(R.id.captureImage);
mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView);
captureImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//this button press should take the picture
}
});
mSurfaceView.getHolder().addCallback(this);
mSurfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mCamera = Camera.open();
}
#Override
public void onPause() {
super.onPause();
mCamera.stopPreview();
}
#Override
public void onDestroy() {
super.onDestroy();
mCamera.release();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera.setPreviewDisplay(mSurfaceView.getHolder());
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Camera.Parameters params = mCamera.getParameters();
List<Camera.Size> sizes = params.getSupportedPreviewSizes();
Camera.Size selected = sizes.get(0);
params.setPreviewSize(selected.width,selected.height);
mCamera.setParameters(params);
mCamera.setDisplayOrientation(90);
mCamera.startPreview();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
I need to get the bytes [] data so that I can convert the image to a base64 string. How do I call the necessary methods to take the picture using the code above?
Check "jpegCallback" in my example:
public class CameraActivity extends ActionBarActivity implements SurfaceHolder.Callback {
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
PictureCallback jpegCallback;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
surfaceHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d("Log", "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Toast.makeText(getApplicationContext(), "Picture Saved", 2000).show();
refreshCamera();
}
};
}
public void captureImage(View v) throws IOException {
//take the picture
camera.takePicture(null, null, jpegCallback);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
// open the camera
camera = Camera.open();
} catch (RuntimeException e) {
// check for exceptions
System.err.println(e);
return;
}
Camera.Parameters param;
param = camera.getParameters();
// modify parameter
List<Camera.Size> sizes = param.getSupportedPreviewSizes();
Camera.Size selected = sizes.get(0);
param.setPreviewSize(selected.width,selected.height);
camera.setParameters(param);
try {
// The Surface has been created, now tell the camera where to draw
// the preview.
camera.setDisplayOrientation(90);
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (Exception e) {
// check for exceptions
System.err.println(e);
return;
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
refreshCamera();
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
// stop preview and release camera
camera.stopPreview();
camera.release();
camera = null;
}
public void refreshCamera() {
if (surfaceHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
camera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (Exception e) {
}
}
}
How to take and save image on click using Custom camera and show the saved image on next Activity's Screen. (with PostTask )
Here is the what i have tried...
1.Camera Activity
public static final int CAMERA_REQUEST = 1000;
private FrameLayout cameraPreview;
private Camera mCamera;
private CameraPreview mCameraPreview;
private Camera_Activity screen;
private final Context context = this;
capture_snap.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
PostTask pt = new PostTask();
pt.execute(screen);
pdialog = new ProgressDialog(Camera_Activity.this);
pdialog.setCancelable(false);
pdialog.setMessage("Please Wait...");
pdialog.show();*/
}
});
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
System.out.println("picture file is null");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpeg");
return mediaFile;
}
private class PostTask extends AsyncTask<Activity, String, String>
{
#Override
protected String doInBackground(Activity... params) {
return "";
}
protected void onPostExecute(String result) {
if(pdialog != null)
{
pdialog.setCancelable(true);
pdialog.dismiss();
Intent i=new Intent(getApplicationContext(),Camera_view.class);
//i.putExtra(mediaFile, mediaFile);
startActivity(i);
}
else{
pdialog.setCancelable(true);
pdialog.dismiss();
MessageDialog.showMessage("Alert",
"Incorrect Path", Camera_Activity.screen);
}
}
}
private void releaseCamera(){
if (mCamera != null){
mCameraPreview.getHolder().removeCallback(mCameraPreview);
mCamera.release(); // release the camera for other applications
}
}
2.Camera Preivew
public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
// Constructor that obtains context and camera
#SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
// left blank for now
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
//mCamera.stopPreview();
//mCamera.release();
if(mCamera != null){
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
}
}
public void onPause() {
mCamera.stopPreview();
//mCamera = null;
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
}
3.Camera View //Here i am trying show captured image...
go through with this tutorial dude
http://www.androidhive.info/2013/09/android-working-with-camera-api/
I’m a beginner and I need help. How do I take photos with camera and save or send to next activity?
I've tried a couple of options, i.e. takepicture with picture callback and surfaceview/take with intent. However, neither works properly on Android 2.3.3. Could someone figure out the issues with my code below?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sf_foto);
mCamera = getCameraInstance();
mCameraPreview = new SF_CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
ImageButton captureButton = (ImageButton) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(myShutterCallback, mPicture_RAW, mPicture);
}
});
}
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open(0);
camera.setDisplayOrientation(90);
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {}
};
PictureCallback mPicture_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {}
};
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Intent i = new Intent(StyloveFoto.this, Filter.class);
startActivity(i);
}
};
protected File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),"KWAlbum");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("KWAlbum", "failed to create directory");
return null;
}
}
// Create a media file name
File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "KW" + ".jpg");
return mediaFile;
}
my surface view:
public class SF_CameraPreview extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
public SF_CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
// left blank for now
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
//mCamera.stopPreview();
mCamera.release();
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
mCamera.setPreviewDisplay(surfaceHolder);
Camera.Parameters parameters = mCamera.getParameters();
parameters.set("orientation", "portrait");
mCamera.setParameters(parameters);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
}
instead of this line : fos.write(data);
write : fos.write(data,0,data.length);
if you want to pass it to the next activity:
Intent i = new Intent(StyloveFoto.this, Filter.class);
i.putExtra("myImage",data);
startActivity(i);
and then in class filter in the oncreate method
byte[] myImage = getIntent()getIntent().getByteArrayExtra("myImage");
I got the same problem and i just solve it before.
The problem is that mPicture is an object of PictureCallback. You can't set intent directing to Filter.class from StyloveFoto.this, because it is in PictureCallback interface. Try this one:
Intent i = new Intent(getBaseContext() , Filter.class);
startActivity(i);
Such a big trap in java....hope it helps :)
Either you save the picture like this and pass the path to another activity
final File file = new File(Environment.getExternalStorageDirectory() + "/" + System.currentTimeMillis() + "_pic.jpg");
OutputStream output = null;
try {
output = new FileOutputStream(file);
output.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != output) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
OR
Pass data from camera activity :
Intent intent = new Intent(getApplicationContext(), your_class.class);
intent.putExtra("path", path);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Receiving Activity
byte[] data = getIntent().getByteArrayExtra("path");
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
image.setImageBitmap(scaleDownBitmapImage(bitmap, 300, 200));
I am trying to do an application that takes a picture with the front facing camera without a UI and i have been successful doing that but the only problem is the picture is always taken in landscape mode, is there any ways to force it to portrait mode?
public class TakePicture extends Activity implements SurfaceHolder.Callback
{
private ImageView iv_image;
private SurfaceView sv;
private Bitmap bmp;
private SurfaceHolder sHolder;
private Camera mCamera;
private int cameraId = 1;
private Parameters parameters;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv_image = (ImageView) findViewById(R.id.imageView);
sv = (SurfaceView) findViewById(R.id.surfaceView);
sHolder = sv.getHolder();
sHolder.addCallback(this);
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3)
{
parameters = mCamera.getParameters();
mCamera.setParameters(parameters);
mCamera.startPreview();
//mCamera.setDisplayOrientation(90);
//sets what code should be executed after the picture is taken
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
Log.d("DEBUG", "Can't create directory to save image.");
Toast.makeText(TakePicture.this, "Can't create directory to save image.",
Toast.LENGTH_LONG).show();
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "Picture_" + date + ".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(TakePicture.this, "New Image saved:" + photoFile,
Toast.LENGTH_LONG).show();
finish();
} catch (Exception error) {
Log.d("DEBUG", "File" + filename + "not saved: "
+ error.getMessage());
Toast.makeText(TakePicture.this, "Image could not be saved.",
Toast.LENGTH_LONG).show();
}
}
};
mCamera.takePicture(null, null, mCall);
}
public void surfaceCreated(SurfaceHolder holder)
{
// The Surface has been created, acquire the camera and tell it where
// to draw the preview.
//mCamera = Camera.open();
mCamera = Camera.open(cameraId);
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}
public void surfaceDestroyed(SurfaceHolder holder)
{
//stop the preview
mCamera.stopPreview();
//release the camera
mCamera.release();
//unbind the camera from this object
mCamera = null;
}
private File getDir() {
File sdDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "Camera!");
}
}
As far as I remember when trying to do this, it was a bit tricky.
One approach I found was:
public void surfaceCreated(SurfaceHolder holder) {
mCamera = Camera.open();
Parameters params = mCamera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
params.set("orientation", "portrait");
try {
//not sure if this block of code had an OR relationship with the previous line params.set("orientation", "portrait");
Method rotateSet = Camera.Parameters.class.getMethod("setRotation", new Class[] { Integer.TYPE });
Object arguments[] = new Object[] { new Integer(90) };
rotateSet.invoke(params, arguments);
} catch (Exception e) {
e.printStackTrace();
}
}
mCamera.setParameters(params);
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}
But it didn't work for me (althought I was using Android version higher than 2.0, where this was supposed to work).
I also found a hack using reflection, and that worked:
public void surfaceCreated(SurfaceHolder holder) {
mCamera = Camera.open();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {}
setDisplayOrientation(mCamera, 90);
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}
Where setDisplayOrientation is:
protected void setDisplayOrientation(Camera camera, int angle){
Method setDisplayOrientationMethod;
try {
setDisplayOrientationMethod = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
if (setDisplayOrientationMethod != null) {
setDisplayOrientationMethod.invoke(camera, new Object[] {angle});
}
} catch (Exception e1) {}
}