简体   繁体   English

android中的图像捕获仅在手机中的模拟器上有效

[英]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. 使用android内置相机拍摄图像并将图像保存在SD卡中。 The code is working fine with the emulator. 该代码在模拟器上运行良好。 But when i installed the apk in phone(samsung galaxy s3). 但是当我在手机(三星银河s3)中安装apk时。 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. 我已经将apk安装在手机上,然后单击第一个图像中提到的相机按钮,仅显示“相机发布的吐司”。

Is it necessary to load preview in our page? 是否需要在我们的页面中加载预览?

i am very new with camera API. 我对相机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 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 您是否将此权限添加到AndroidManifest.xml文件

<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);


        }


    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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