Android中的自定义相机拍摄的图像并不清晰

时间:2017-01-23 09:31:37

标签: java android android-camera surface

我在我的应用中使用自定义相机创建了一个多图像捕捉功能。但是自定义相机存在问题。自定义相机拍摄的图像不像默认相机那样清晰(使用Intent打开相机) 请帮帮我。我已经尝试了很多建议的解决方案。

CameraActivity.java

public class CameraActivity extends Activity {


 private Camera                      mCamera;
 private SharedPreferences           prefs;             
 private String                      clickedMenuItem;
 Button                              captureButton;
 private LayoutInflater              controlInflater = null;
 private View                        viewControl;
 private CircularImageView           imgview;
 private ArrayList<Bitmap>           bitmapArray = new ArrayList<Bitmap>();;
 private ImageView                   cancleimg;
 private FrameLayout                 imgLayout;
 int                                 RESULT_IMG = 200;
 int                                 NO_IMG = 204;
 FrameLayout                         preview;
 private CameraPreview               mCameraPreview;
 ArrayList<CharSequence>             imgarrayList = new ArrayList<CharSequence>();
 Intent                              intent = new Intent(        );

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera_preview);

        clickedMenuItem = Attributes.Another_Item; 
        if(getIntent().hasExtra(Attributes.ClickedMenuItem)){
        clickedMenuItem = getIntent().getExtras().getString(Attributes.ClickedMenuItem); 
        }

        mCamera = getCameraInstance();
        mCameraPreview = new CameraPreview(this, mCamera);
        preview = (FrameLayout) findViewById(R.id.camera_preview);
        preview.addView(mCameraPreview);

        try{
            controlInflater = LayoutInflater.from(getBaseContext());
            viewControl = controlInflater.inflate(R.layout.control, null);
            LayoutParams layoutParamsControl
            = new LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.FILL_PARENT);

            this.addContentView(viewControl, layoutParamsControl);
            }catch(Exception e)
            {e.printStackTrace();}
        captureButton = (Button)viewControl.findViewById(R.id.button_capture);
        Button doneBtn = (Button)viewControl.findViewById(R.id.done);
        imgview = (CircularImageView)viewControl.findViewById(R.id.captureimg);
        cancleimg = (ImageView)viewControl.findViewById(R.id.cancleimg);
        imgLayout = (FrameLayout)viewControl.findViewById(R.id.imglayout);
        imgLayout.setVisibility(View.INVISIBLE);
        if (isDIYUSer() && clickedMenuItem != null && !clickedMenuItem.equals(Attributes.Kagazz_Scanner)) {
            captureButton.setBackgroundResource(R.drawable.cam);
        }

        cancleBtnClick();

        captureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCamera.takePicture(null, null, mPicture);
            }
        });

        doneBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                setResult(RESULT_IMG,intent);
                bitmapArray = null;
                finish();

            }
        });

    }

    @Override
    public void onPause() {
         try{
        super.onPause();
        releaseCamera();   
        }catch(Exception e)
        {}// release the camera immediately on pause event
    }

    private void releaseCamera(){
        try{
            if (mCamera != null){
                mCamera.stopPreview(); 
                mCamera.setPreviewCallback(null);// stop the preview
                mCamera.release();  
                preview.removeView(mCameraPreview);
                mCamera = null;
                // release the camera for other applicationsCODE_IMG

            }
        }
        catch(Exception e)
        {}
   }
    @Override
    public void onBackPressed() {

         imgarrayList.clear();
         intent.putCharSequenceArrayListExtra("List",imgarrayList);
         setResult(RESULT_IMG,intent);
         finish();

    }

    void cancleImg()
    {}

    public void  deleteTempImg(Uri uri)
    {
        try {
         File file = new File(uri.getPath());
         boolean isdeleted = file.delete();
         if(file.exists()){

           boolean deleted = file.getCanonicalFile().delete();

           if(deleted)
           {Log.d("tag", "file deleted.");}

         } 
               if(file.exists()){
                    this.getApplicationContext().deleteFile(file.getName());
               }
         }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    @Override
    public void onResume() {
        super.onResume();
        try{    
        if (mCamera == null)
        {
            mCamera = getCameraInstance();
            // three new lines, creating a new CameraPreview, then adding it to the FrameLayout
            mCameraPreview = new CameraPreview(this, mCamera);
            preview = (FrameLayout) findViewById(R.id.camera_preview);
            preview.addView(mCameraPreview);
        }
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }


    /**
     * Helper method to access the camera returns null if it cannot get the
     * camera or does not exist
     *
     * @return
     */
    private Camera getCameraInstance() {
       mCamera = null;
        try {
            mCamera = Camera.open();

          //STEP #1: Get rotation degrees
          //  Camera.CameraInfo info = new Camera.CameraInfo();
          //  Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, info);
           // int rotation = this.getWindowManager().getDefaultDisplay().getRotation();
           // int degrees = 0;
          //  switch (rotation) {
          //      case Surface.ROTATION_0: degrees = 0; break; //Natural orientation
         //           case Surface.ROTATION_90: degrees = 90; break; //Landscape left
         //           case Surface.ROTATION_180: degrees = 180; break;//Upside down
         //           case Surface.ROTATION_270: degrees = 270; break;//Landscape right
         //       }
         //   int rotate = (info.orientation - degrees + 360) % 360;

            //STEP #2: Set the 'rotation' parameter
            Camera.Parameters params = mCamera.getParameters();
          //  params.setRotation(rotate); 
            /* Set Auto focus */ 

            List<String> focusModes = params.getSupportedFocusModes();
            if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
                // set the focus mode
                params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
                // set Camera parameters


            }
            else{
                 if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE))
                params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            }
            mCamera.setParameters(params);
        } catch (Exception e) {
            // cannot get camera or does not exist
        }
        return mCamera;
    }




    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 + ".jpg");

        return mediaFile;
    }

    public static Bitmap rotate(Bitmap bitmap, int degree) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        Matrix mtx = new Matrix();
       //       mtx.postRotate(degree);
        mtx.setRotate(degree);

        return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
    }
    @Override
    protected void onStop() {
        super.onStop();
    }

}

CameraPreview.java

    public class CameraPreview extends SurfaceView implements
     SurfaceHolder.Callback {

    private SurfaceHolder mSurfaceHolder;
    private Camera mCamera;
    private LayoutInflater controlInflater = null;
    // 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 {       
            @SuppressWarnings("deprecation")
            Camera.Parameters parameters = mCamera.getParameters();
            if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
                 parameters.set("orientation", "portrait");
                 mCamera.setDisplayOrientation(90);
                 parameters.setRotation(90);
            }
                 else {
                      // This is an undocumented although widely known feature
                      parameters.set("orientation", "landscape");
                      // For Android 2.2 and above
                      mCamera.setDisplayOrientation(0);
                      // Uncomment for Android 2.0 and above
                      parameters.setRotation(0);
            }
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();

        } catch (IOException e) {
        }


}

@SuppressWarnings("deprecation")
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
    try{
         surfaceHolder.removeCallback(this);
         mCamera.stopPreview();
         mCamera.release(); 
         mCamera = null;
    }catch(Exception e)
    {
        if(e!=null)
        e.printStackTrace();}

}
@SuppressWarnings("deprecation")
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
                       int width, int height) {
// start preview with new settings
        try {
            mCamera.setPreviewDisplay(surfaceHolder);

            mCamera.startPreview();
        } catch (Exception e) {
            // intentionally left blank for a test
        }
}

}

0 个答案:

没有答案