簡體   English   中英

android中的圖像捕獲僅在手機中的模擬器上有效

[英]Image capturing in android is working only on emulator not in phone

我已經遵循

使用android內置相機拍攝圖像並將圖像保存在SD卡中。 該代碼在模擬器上運行良好。 但是當我在手機(三星銀河s3)中安裝apk時。 該應用程序將不會拍攝圖像。

我的代碼如下。 請看一看。

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

點擊拍照

圖像保存在該位置

在此處輸入圖片說明

我已經將apk安裝在手機上,然后單擊第一個圖像中提到的相機按鈕,僅顯示“相機發布的吐司”。

是否需要在我們的頁面中加載預覽?

我對相機API很陌生。

請指導我解決這個問題

謝謝

這是我自己的博客,您將在其中獲得關於問題的描述。 http://uniqueandroidtutorials.blogspot.in/2013/02/code-to-start-camera-with-build-in.html

希望對您有幫助。。謝謝

您是否將此權限添加到AndroidManifest.xml文件

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

然后參考此代碼。 它對我有用。

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