简体   繁体   中英

Android: Camera surfaceview is blurry

I am building my own camera app using the android camera api. I have a working app but the preview is not as sharp as the default camera app. Why is this the case? Here is my code below.

public class showCamera  extends SurfaceView implements SurfaceHolder.Callback {

       private static final int PICTURE_SIZE_MAX_WIDTH =640;
        private static final int PREVIEW_SIZE_MAX_WIDTH = 640;
    //private Camera theCamera;
    private SurfaceHolder holdMe;
       private Camera theCamera;
        int h;
       int w;

    public showCamera (Context context,Camera camera,int w,int h)
    {
          super(context);
          theCamera = camera;
          holdMe = getHolder();
          holdMe.addCallback(this);
          this.h=h;
          this.w=w;




    }

    public showCamera(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        // TODO Auto-generated method stub





    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        try   {
             theCamera.setPreviewDisplay(holder);
                //setDisplayOrientation(theCamera,90);
            if( (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ))
            { theCamera.setDisplayOrientation(90); 
            }


            Camera.Parameters parameters = theCamera.getParameters();
            Log.d("     " , " THIS IS THE FLASH MODE = " + parameters.getFlashMode()) ;
             List<String> g=  parameters.getSupportedFocusModes();

             for(int j=0;j<g.size();j++)
             {
                 Log.d("     " , " THIS IS focus modes =" + g.get(j)) ;

             }

            Size bestPreviewSize = determineBestPreviewSize(parameters);
            Size bestPictureSize = determineBestPictureSize(parameters);

            parameters.setPreviewSize(bestPreviewSize.width, bestPreviewSize.height);
            parameters.setPictureSize(bestPictureSize.width, bestPictureSize.height);
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            theCamera.setParameters(parameters);

             theCamera.startPreview(); 








          } catch (IOException e) {
          }


    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
         theCamera.stopPreview();
         theCamera.release();
        // TODO Auto-generated method stub

    }
     protected void setDisplayOrientation(Camera camera, int angle){
            Method downPolymorphic;
            try
            {
                downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
                if (downPolymorphic != null)
                    downPolymorphic.invoke(camera, new Object[] { angle });
            }
            catch (Exception e1)
            {
            }
        }

     private Size determineBestPreviewSize(Camera.Parameters parameters) {
            List<Size> sizes = parameters.getSupportedPreviewSizes();

            return determineBestSize(sizes, PREVIEW_SIZE_MAX_WIDTH);
        }

        private Size determineBestPictureSize(Camera.Parameters parameters) {
            List<Size> sizes = parameters.getSupportedPictureSizes();

            return determineBestSize(sizes, PICTURE_SIZE_MAX_WIDTH);
        }





     protected Size determineBestSize(List<Size> sizes, int widthThreshold) {
            Size bestSize = null;

            for (Size currentSize : sizes) {
                boolean isDesiredRatio = (currentSize.width / 4) == (currentSize.height / 3);
                boolean isBetterSize = (bestSize == null || currentSize.width > bestSize.width);
                boolean isInBounds = currentSize.width <= PICTURE_SIZE_MAX_WIDTH;

                if (isDesiredRatio && isInBounds && isBetterSize) {
                    bestSize = currentSize;
                }
            }

            if (bestSize == null) {


                return sizes.get(0);
            }

            return bestSize;
        }





     AutoFocusCallback autoFocusCallback = new AutoFocusCallback() {
          @Override
          public void onAutoFocus(boolean success, Camera camera) {
            Log.i("tag","this ran sdfgfhgjkldxbvnm,jhgfdkmn" ); 

          }
        };









}

MainActivity

 public class MainActivity extends Activity implements OnClickListener {

    private Camera cameraObject;
    private showCamera showCamera;
    int h;
    int w = 1080;
    LinearLayout Top, Buttom;
    Button b;

    public static Camera isCameraAvailiable() {
        Camera object = null;
        try {

            object = Camera.open();
            object.getParameters();

        } catch (Exception e) {
        }
        return object;
    }

    AutoFocusCallback autoFocusCallback = new AutoFocusCallback() {
        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            Log.i("tag", "this ran sdfgfhgjkldxbvnm,jhgfdkmn");

        }
    };

    private PictureCallback capturedIt = new PictureCallback() {

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

            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            if (bitmap == null) {
                Toast.makeText(getApplicationContext(), "not taken",
                        Toast.LENGTH_SHORT).show();
            } else {
                File pictureFile = MediaOutput();
                if (pictureFile == null) {
                    Log.d("",
                            "Error creating media file, check storage permissions: ");
                    return;
                }

                try {
                    FileOutputStream fos = new FileOutputStream(pictureFile);
                    fos.write(data);
                    MediaStore.Images.Media.insertImage(getContentResolver(),
                            bitmap, "testing ", "");
                    Toast.makeText(getApplicationContext(), "taken",
                            Toast.LENGTH_SHORT).show();
                    fos.close();
                } catch (FileNotFoundException e) {
                    Log.d("", "File not found: " + e.getMessage());
                } catch (IOException e) {
                    Log.d("", "Error accessing file: " + e.getMessage());
                }

            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camlay);
        Top = (LinearLayout) findViewById(R.id.top_bar);
        Buttom = (LinearLayout) findViewById(R.id.but_bar);
        b = (Button) findViewById(R.id.but_pic);
        b.setOnClickListener(this);
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int width = size.x;
        int height = size.y;

        h = (int) Math.round(0.8 * height);

        Log.d(" ", "  height " + h);
        Log.d(" ", "  width " + width);
        Top.setLayoutParams(new LinearLayout.LayoutParams(width, (int) Math
                .round(0.10 * height)));
        Buttom.setLayoutParams(new LinearLayout.LayoutParams(width, (int) Math
                .round(0.10 * height)));

        cameraObject = isCameraAvailiable();
        showCamera = new showCamera(this, cameraObject, width, h);
        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);

        preview.addView(showCamera, new FrameLayout.LayoutParams(width, h));
        // preview.addView(showCamera);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        switch (v.getId()) {
        case R.id.but_pic:
            // cameraObject.takePicture(null, null,capturedIt);

            // parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            Camera.Parameters parameters = cameraObject.getParameters();

            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            cameraObject.setParameters(parameters);

            cameraObject.autoFocus(autoFocusCallback);
            // cameraObject.stopPreview();

            break;
        }

    }

    private static File MediaOutput() {
        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;
            }
        }

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");

        return mediaFile;

    }

}

If you can point me in the right direction that would be great.

Did you ever tried to increase these values in your showCamera class:

    private static final int PICTURE_SIZE_MAX_WIDTH = 640;
    private static final int PREVIEW_SIZE_MAX_WIDTH = 640;

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