0

我正在开发这个需要访问相机的应用程序。我已经很好地访问了它。但是有两个问题。手机垂直时,预览全部拉伸。其次,当我恢复应用程序时,相机预览不可见。camera.open() 函数确实会打开相机,但我看不到预览。我已经尝试了论坛上提供的所有帮助,但实际上并没有解决我的问题。

-提前致谢!

//Camera Activity file

@SuppressLint("SimpleDateFormat")
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
private FrameLayout preview;
private Button bCapture;
private Button bGallery;
private static final String TAG = "CameraActivity";
private static final int PICK_IMAGE_REQUEST = 1;
private TextView tvCheck;
public final static String EXTRA_MESSAGE = "com.epfl.mycamera.MESSAGE";    
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_camera);
    if (checkCameraHardware(getBaseContext())){
        // 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, CameraActivity.this);
        preview = (FrameLayout) findViewById(R.id.camera_preview);
        preview.addView(mPreview);
        //Adding Camera Button
        bCapture = (Button) findViewById(R.id.bCapture);
        //Button Listener for storing images
        bCapture.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCamera.takePicture(null, null, null, jpegCallback);
                mCamera.startPreview();
                Log.d(TAG, "takePicture");
            }
        });
        //Adding Gallery Button
        bGallery = (Button) findViewById (R.id.bGallery);
        bGallery.setOnClickListener(new View.OnClickListener() {        
            @Override
            public void onClick(View v) {
                tvCheck = (TextView) findViewById (R.id.tvCheck);
                selectImageFromGallery();
            }
        });
    }
        Log.d(TAG, "OnCreate");
}
/******************************************************************/

public void selectImageFromGallery() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE_REQUEST);
}

@Override
protected void onActivityResult(int aRequestCode, int aResultCode, Intent aData) {
    switch (aRequestCode) {
        case PICK_IMAGE_REQUEST:
            handleImage(aData);
            break;
        default: 
            tvCheck.setText("You can only select images.");
            break;
    }
    super.onActivityResult(aRequestCode, aResultCode, aData);
}


private void handleImage(Intent aData) {
    if ((aData != null) && (aData.getData() != null)) {
        Uri selectedImage = aData.getData();
        String[] filePathColumn = {MediaColumns.DATA};
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        Log.d("ImageActivity", "After extracting file Path");
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        Log.d("ImageActivity", "After closing the cursor");
        setContentView(R.layout.activity_image_old); //setting the view to the image
        ImageView imgView = (ImageView) findViewById(R.id.ivGallery);
        imgView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        Button bLiveCamera = (Button) findViewById(R.id.bCameraPreview);
        bLiveCamera.setOnClickListener(new View.OnClickListener() {        
            @Override
            public void onClick(View v) {
                setContentView(R.layout.activity_camera);
                mCamera.startPreview();
            }
        });
    } 
    else {
        tvCheck.setText("You did not select an image");
    }
}

/****************************************************************/

/** Stores jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
    public void onPictureTaken(byte[] data, Camera camera) {
        try {
            File mediaStorageDir = new File(Environment                             .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyCamera");
            // Saving image to the SD CARD with a file operation
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            File mediaFile;
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +"IMG_"+ timeStamp + ".jpg");
            FileOutputStream outStream = new FileOutputStream(mediaFile);   
            outStream.write(data);
            outStream.close();
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
            Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }      Log.d(TAG, "onPictureTaken - jpeg");
    }
};


/***************************************************************/

/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
    if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
         Log.d(TAG, "Camera Available");
        return true;
    } else {
        Log.d(TAG, "No Camera Found");
        return false;
    }
}

/** A safe way to get an instance of the Camera object. */
public Camera getCameraInstance(){
    Camera c = null;
    try {
        int i = Camera.getNumberOfCameras();
        releaseCamera(); //in case camera is being accessed by any other app.
        Log.d(TAG, "Number of Cameras "+i +"\n");
        c = Camera.open(); // attempt to get a Camera instance
        Log.d(TAG, "Camera Opened");
    }
    catch (Exception e){
         Log.d(TAG, "Camera Can't Be Accessed");
    }
    return c; // returns null if camera is unavailable
}


 @Override
    protected void onPause() {
        super.onPause();
        releaseCamera();              // release the camera immediately on pause event
    }

    private void releaseCamera(){
        if (mCamera != null){
            mPreview.getHolder().removeCallback(mPreview);
            mCamera.release();        // release the camera for other applications
        }
    }

    @Override
    public void onResume() {
        super.onResume();  
        // Get the Camera instance as the activity achieves full user focus
        if (mCamera == null) {
           getCameraInstance();  
           mCamera.startPreview();
        }
    }

}

这是我的相机预览课:

@SuppressLint({ "ViewConstructor", "SdCardPath" })
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "CameraPreview";
private SurfaceHolder mHolder;
private Camera mCamera;
private Size mPreviewSize; 
// private Activity CameraActivity;

@SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera, Activity activity) {
    super(context);
    mCamera = camera;
    //CameraActivity = activity;
    // Install a SurfaceHolder.Callback so we get notified when the
    // underlying surface is created and destroyed.
    mHolder = getHolder();
    mHolder.addCallback(this);
    mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

public void surfaceCreated(SurfaceHolder holder) {
    // The Surface has been created, now tell the camera where to draw the preview.     
    try {
        mCamera.setPreviewDisplay(holder);
        //add camera preview call back here.
        mCamera.startPreview();
    } catch (IOException e) {
        Log.d(TAG, "Error setting camera preview: " + e.getMessage());
    }
}


public void surfaceDestroyed(SurfaceHolder holder) {
    // empty. Take care of releasing the Camera preview in your activity.

}

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    // If your preview can change or rotate, take care of those events here.
    // Make sure to stop the preview before resizing or reformatting it.

    if (mHolder.getSurface() == null){
      // preview surface does not exist
      return;
    }

    // stop preview before making changes
    try{
          mCamera.stopPreview();
        } catch (Exception e){
          // ignore: tried to stop a non-existent preview
        }


    // set preview size and make any resize, rotate or
    // reformatting changes here
    Camera.Parameters parameters = mCamera.getParameters();
    List<Size> localSizes = mCamera.getParameters().getSupportedPreviewSizes();
    mPreviewSize = localSizes.get(0);
    Log.d(TAG, "Width " + mPreviewSize.width);
    Log.d(TAG, "Height " + mPreviewSize.height);

    parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height );
    mHolder.setFixedSize(mPreviewSize.width, mPreviewSize.height);
    requestLayout();
    mCamera.setParameters(parameters);

    //start preview with new settings
    try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.setDisplayOrientation(90);
            //setCameraDisplayOrientation(CameraActivity, 0, mCamera);
            mCamera.startPreview();
    } catch (Exception e){
        Log.d(TAG, "Error starting camera preview: " + e.getMessage());
    }
}
}
4

1 回答 1

3

您仅在 Activity 的 onCreate() 上创建一个 CameraPreview。但是相机实例在onPause() 上被释放,并在onResume() 上打开一个新实例。因此,您需要重新设置曲面。

于 2013-07-15T18:50:27.547 回答