简体   繁体   中英

Image capturing in android is working only on emulator not in phone

I have followed this

to take an image using android inbuilt camera and save the image in sd card. The code is working fine with the emulator. But when i installed the apk in phone(samsung galaxy s3). the application will not take images.

My code is follows. Please have a look.

public class MainActivity extends Activity {
    int TAKE_PHOTO_CODE = 0;
    protected Context context = this;
    public static int count = 0;
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;
    protected static final String TAG = "MyCameraAppss";
private Camera autoCam ;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button capture = (Button) findViewById(R.id.btnCapture);
        capture.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                captureImage();
            }
        });

    }

    private void captureImage(){
        //Detecting camera hardware
        boolean isCameraAvailable = checkCameraHardware(context);
        if(isCameraAvailable){
            Toast.makeText(context, "Camera found", Toast.LENGTH_SHORT).show();
            //Accessing cameras
             autoCam = getCameraInstance();
             if(autoCam!=null){
                 autoCam.open();
                 Toast.makeText(context, "Camera is accesses successfully", Toast.LENGTH_SHORT).show();
                 autoCam.takePicture(null, null, mPicture);
                 Toast.makeText(context, "picture is taken and going to sleep for a sec", Toast.LENGTH_SHORT).show();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
             }else{
                 Toast.makeText(context, "Camera instance not available", Toast.LENGTH_SHORT).show();
             }
             Toast.makeText(context, "After slept going to release the camera", Toast.LENGTH_SHORT).show();
            autoCam.release();
             Toast.makeText(context, "Camera released successfully", Toast.LENGTH_SHORT).show();
        }else{
              Toast.makeText(context, "cannot access the camera", Toast.LENGTH_SHORT).show();
        }
    }

    private PictureCallback mPicture = new PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {

            File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
            if (pictureFile == null){
                  Toast.makeText(context, "Error creating media file, check storage permissions:", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "Error creating media file, check storage permissions: ");
                return;
            }else{
                 Toast.makeText(context, "Save: Pic file is found going to write", Toast.LENGTH_SHORT).show();
            }

            try {
                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(data);
                fos.close();
                Toast.makeText(context, "Save: Pic is saved successfully", Toast.LENGTH_SHORT).show();
            } catch (FileNotFoundException e) {
                  Toast.makeText(context,  "File not found: " + e.getMessage(), Toast.LENGTH_LONG).show();
                Log.d(TAG, "File not found: " + e.getMessage());
            } catch (IOException e) {
                 Toast.makeText(context,  "Error accessing file: " + e.getMessage(), Toast.LENGTH_LONG).show();
                Log.d(TAG, "Error accessing file: " + e.getMessage());
            }catch (Exception e) {
                 Toast.makeText(context,  "Other Exception: " + e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    };
    /** Check if this device has a camera */
    private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }
    /** A safe way to get an instance of the Camera object. */
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
            e.printStackTrace();
        }
        return c; // returns null if camera is unavailable
    }
    /** Create a File for saving an image or video */
    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+"Amith" + ".jpg");
        } else if(type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
            "VID_"+ timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }
} 

点击拍照

The image is saved in the location

在此处输入图片说明

I have installed the apk on my phone and clicks the camera button mentioned in the first image, only "camera released toast" is displayed.

Is it necessary to load preview in our page?

i am very new with camera API.

Please guide me to resolve this

Thank you

This is my own blog here you will get description of your problem. http://uniqueandroidtutorials.blogspot.in/2013/02/code-to-start-camera-with-build-in.html

Hope it will helps you..Thanks

Did you add this permission to AndroidManifest.xml file

<uses-feature android:name="android.hardware.camera" />

Then refer this codes. It work for me.

private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;

private Uri fileUri; 
private static int RESULT_LOAD_IMAGE = 1;


 public void captureImage() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());

        fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

        // start the image capture Intent
        startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);


    }

    /**
     * Here we store the file url as it will be null after returning from camera
     * app
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        // save file url in bundle as it will be null on scren orientation
        // changes
        outState.putParcelable("file_uri", fileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        // get the file url
        fileUri = savedInstanceState.getParcelable("file_uri");
    }


    /**
     * ------------ Helper Methods ---------------------- 
     * */

    /**
     * Creating file uri to store image
     */
    public Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /**
     * returning image / video
     */
    private static File getOutputMediaFile(int type) {

        // External sdcard location
        if(latlon==null)
            latlon="";

        File mediaStorageDir = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator  + "CERS");

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {

                return null;
            }
        }

        // Create a media file name
        File mediaFile;



        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath()+  File.separator+ timeStamp + "_--"+ latlon +"--.jpg");
        } 

        return mediaFile;
    }

private void previewCapturedImage() {
    try {


         // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // downsizing image as it throws OutOfMemory Exception for larger
        options.inSampleSize = 8;

        final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);


        IMGS.setImageBitmap(bitmap);


    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}
  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // if the result is capturing Image
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // successfully captured the image
                // display it in image view
                previewCapturedImage();
            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled Image capture
                toast.ShowAlert("User cancelled image capture", 0,false);

            } else {
                // failed to capture image
                toast.ShowAlert("Sorry! Failed to capture image",0,false);
            }
        } 

        /***/
        /** Browse Images **/
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 8;
            final Bitmap bitmap = BitmapFactory.decodeFile(picturePath, options);

            IMGS.setImageBitmap(bitmap);


        }


    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM