Android Камера библиотеки сбивает с толку. Не могу нажать на фотографию с максимальным разрешением - PullRequest
0 голосов
/ 30 апреля 2020

Мне нужно, чтобы камера щелкала фото с максимальным разрешением, поддерживаемым камерой, используя более старый API «Камера». Проблема заключается в следующем: когда я выбираю разрешение изображения из списка в методе «openChoosePictureResolution ()», я могу щелкнуть изображение с максимально возможным разрешением. Но если я не выберу разрешение, камера сделает снимки с самым низким разрешением, т.е. 176x144 пикселей. Я просто не хочу, чтобы пользователь выбирал разрешение и всегда делал снимки в самом высоком поддерживаемом разрешении. Пожалуйста помоги.

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


public class Camera1_FullScr extends Activity implements OnClickListener {

    private int cameraId = 0;
    private android.hardware.Camera camera = null;
    String formattedDate;
//    TextView tv_select_res;

    Button capture_btn;
//    AudioManager audioManager;

    Boolean bool=true;
    int max_pic_width=0, max_pic_height=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.fullscr_cam);
//        tv_select_res = (TextView) findViewById(R.id.sel_res);
//        tv_select_res.setTextColor(getResources().getColor(R.color.GrayDolphin));
        capture_btn = (Button) findViewById(R.id.capture_button);
        capture_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    camera.takePicture(null, null, pictureCallback);
                    showAutoCloseDialog();
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "an Error: " + e + " occured", Toast.LENGTH_SHORT).show();
                    Toast.makeText(getApplicationContext(), "Make Sure you've granted all the Permissions the app needs by going to app settings.", Toast.LENGTH_LONG).show();
                }
            }
        });

        Button switchCamButton = (Button) findViewById(R.id.switch_button);
        switchCamButton.setOnClickListener( new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent frontCamAct = new Intent(Camera1_FullScr.this, Camera1_FullScr_Front.class);
                Camera1_FullScr.this.finish();
                startActivity(frontCamAct);
            }
        });

//        audioManager = (AudioManager) getSystemService(getApplicationContext().AUDIO_SERVICE);
        Toast.makeText(getApplicationContext(), "onCreate:" + max_pic_width+":" + max_pic_height, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onClick(View v) {
//        Toast.makeText(getApplicationContext(),"ONE", Toast.LENGTH_LONG).show();
        // Toast below shown once  - Vik -
        Toast.makeText(getApplicationContext(), "onClick:" + max_pic_width+":" + max_pic_height, Toast.LENGTH_LONG).show();
        try {
//            Toast.makeText(getApplicationContext(),"TWO", Toast.LENGTH_LONG).show();
            capture_btn.setVisibility(View.VISIBLE);
//            if (v.getTag() != null && v.getTag().getClass() == android.hardware.Camera.Size.class) {
                android.hardware.Camera.Size sz = (android.hardware.Camera.Size) v.getTag();
                Log.e("VAID secretCam", "setPictureSize " + sz.width + "x" + sz.height);
                setPictureSize(max_pic_width, max_pic_height);
//            setPictureSize(640, 480);  //WORKING  - VIK -
                ((View) v.getParent()).setVisibility(View.INVISIBLE);
//                tv_select_res.setVisibility(View.INVISIBLE);


//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
//        Log.d("VAID secretCam", "onResume");
//        Toast.makeText(getApplicationContext(), "onResumee:" + max_pic_width+":" + max_pic_height, Toast.LENGTH_LONG).show();

//        Toast.makeText(getApplicationContext(), "Please find the little ViewFinder at the Bottom Right corner. This can be hidden merely by a finger.", Toast.LENGTH_LONG).show();
        Toast.makeText(getApplicationContext(), "Use Volume buttons to take photos.", Toast.LENGTH_LONG).show();

        setSurface();
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private android.hardware.Camera.PictureCallback pictureCallback = new android.hardware.Camera.PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, android.hardware.Camera camera) {
            try {
                File camDirectory = new File(GlobalClass.camfoldername);
                camDirectory.mkdirs();

                getDateTime();
                FileOutputStream jpg = new FileOutputStream(GlobalClass.camfoldername + "/" + GlobalClass.vrespic + formattedDate + ".jpg");
                jpg.write(data);
                jpg.close();

                try {
                    Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
                    createnomedia();
//                    Log.i("VAID secretCam", "bmp dimensions " + bmp.getWidth() + "x" + bmp.getHeight());
                    camera.startPreview();
                } catch (OutOfMemoryError e) {
                    Toast.makeText(getApplicationContext(), "Out Of Memory, Retry", Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };

    private SurfaceHolder.Callback shCallback = new SurfaceHolder.Callback() {

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
//            Log.i("VAID secretCam", "surfaceDestroyed callback");
            if (camera != null) {
                camera.stopPreview();
                camera.release();
            }
            camera = null;
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
//            Log.i("VAID secretCam", "surfaceCreated callback");
            startCamera(cameraId);
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
//            Log.i("VAID secretCam", "surfaceChanged callback " + width + "x" + height);
            restartPreview();
        }
    };

    private void setSurface() {
        try {
            SurfaceView previewSurfaceView = (SurfaceView) findViewById(R.id.preview_surface);
            previewSurfaceView.getHolder().addCallback(shCallback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void startCamera(final int id) {

        releaseCamera();

        new AsyncTask<Integer, Void, android.hardware.Camera>() {

            @Override
            protected android.hardware.Camera doInBackground(Integer... ids) {
                try {
                    return openCamera(ids[0]);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                return null;
            }

            @Override
            protected void onPostExecute(android.hardware.Camera c) {
                startPreview(id, c);
            }

        }.execute(id);
    }

    private void releaseCamera() {
        try {
            if (camera != null) {
                camera.stopPreview();
                camera.release();
                camera = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void restartPreview() {
        try {
            if (camera == null) {
                return;
            }
            int degrees = 0;
            switch (getWindowManager().getDefaultDisplay().getRotation()) {
                case Surface.ROTATION_0:
                    degrees = 0;
                    break;
                case Surface.ROTATION_90:
                    degrees = 90;
                    break;
                case Surface.ROTATION_180:
                    degrees = 180;
                    break;
                case Surface.ROTATION_270:
                    degrees = 270;
                    break;
            }
            android.hardware.Camera.CameraInfo ci = new android.hardware.Camera.CameraInfo();
            android.hardware.Camera.getCameraInfo(cameraId, ci);
            if (ci.facing == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT) {
                degrees += ci.orientation;
                degrees %= 360;
                degrees = 360 - degrees;
            } else {
                degrees = 360 - degrees;
                degrees += ci.orientation;
            }
            camera.setDisplayOrientation(degrees % 360);
            camera.startPreview();

            openChoosePictureResolution();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void openChoosePictureResolution() {

        try {
            List<android.hardware.Camera.Size> supportedSizes;
            android.hardware.Camera.Parameters params = camera.getParameters();

            supportedSizes = params.getSupportedPictureSizes();

            LinearLayout lv = (LinearLayout) findViewById(R.id.sizes_view);
            lv.removeAllViews();

            for (android.hardware.Camera.Size sz : supportedSizes) {
//                Log.d("VAID secretCam", "supportedPictureSizes " + sz.width + "x" + sz.height);
                TextView item = new TextView(this);
                item.setTextColor(getResources().getColor(R.color.CarbonGray));
                item.setOnClickListener(this);
                item.setText("" + sz.width + "x" + sz.height);
                item.setTextSize(25);
                item.setTag(sz);
                lv.addView(item);
                lv.setVisibility(View.GONE);
//                tv_select_res.setText("Select Resolution");
//                tv_select_res.setVisibility(View.VISIBLE);
                {
                    int max_width=sz.width;
                    int max_height=sz.height;
                    if (bool){
                        max_pic_width=max_width;
                        max_pic_height=max_height;
                        bool=false;
                    }
                }
//                Toast.makeText(getApplicationContext(), "openChoosePicRes:" + max_pic_width+":" + max_pic_height, Toast.LENGTH_LONG).show();
                Log.e("pic width: " + max_pic_width, "pic height: " + max_pic_height);
            }

            lv.setVisibility(View.VISIBLE);
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
    }

    private android.hardware.Camera openCamera(int id) {
        android.hardware.Camera camera = null;
        try {
//            Log.d("VAID secretCam", "opening camera " + id);
            camera = null;
            try {
                camera = android.hardware.Camera.open(0);
//                Log.d("VAID secretCam", "opened camera " + id);
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Sorry!! your device doesn't support Camera1_VF", Toast.LENGTH_LONG).show();
                camera.release();
                camera = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Sorry!! your device doesn't support Camera1_VF", Toast.LENGTH_LONG).show();
        }
        return camera;
    }

    private void setPictureSize(int width, int height) {
        try {
            android.hardware.Camera.Parameters params = camera.getParameters();
            params.setPictureSize(width, height);
            camera.setParameters(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startPreview(int id, android.hardware.Camera c) {
        try {
            if (c != null) {
                try {
                    SurfaceView previewSurfaceView = (SurfaceView) findViewById(R.id.preview_surface);
                    SurfaceHolder holder = previewSurfaceView.getHolder();
                    c.setPreviewDisplay(holder);
                    camera = c;
                    cameraId = id;
                    restartPreview();
                } catch (IOException e) {
                    e.printStackTrace();
                    c.release();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void getDateTime() {
        // TODO Auto-generated method stub
        Calendar c = Calendar.getInstance();
        System.out.println("Current time =&gt; " + c.getTime());

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        formattedDate = df.format(c.getTime());
    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int action = event.getAction();
        int keyCode = event.getKeyCode();
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                if (action == KeyEvent.ACTION_DOWN) {
                    //TODO
                    try {
                        camera.takePicture(null, null, pictureCallback);
                        showAutoCloseDialog();
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "an Error: " + e + " occured", Toast.LENGTH_SHORT).show();
                        Toast.makeText(getApplicationContext(), "Make Sure you've granted all the Permissions the app needs by going to app settings.", Toast.LENGTH_LONG).show();
                    }
//                    audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                }
                return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                if (action == KeyEvent.ACTION_DOWN) {
                    //TODO
                    try {
                        camera.takePicture(null, null, pictureCallback);
                        showAutoCloseDialog();
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "an Error: " + e + " occured", Toast.LENGTH_SHORT).show();
                        Toast.makeText(getApplicationContext(), "Make Sure you've granted all the Permissions the app needs by going to app settings.", Toast.LENGTH_LONG).show();
                    }
//                    audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                }
                return true;
            default:
                return super.dispatchKeyEvent(event);
        }
    }

    public void showAutoCloseDialog() {

        final Dialog autocloseDialog = new Dialog(this);
        autocloseDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        autocloseDialog.setContentView(R.layout.auto_hide_dlg);
//TODO remove title bar
        autocloseDialog.show();

        final Timer t = new Timer();
        t.schedule(new TimerTask() {
            public void run() {
                autocloseDialog.dismiss();
                t.cancel();
            }
        }, 1300);
    }

    public void createnomedia() {
        try {
            File myFile = new File(GlobalClass.camfoldername + "/" + ".nomedia");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
            myOutWriter.close();
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
//        audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
//        Toast.makeText(getApplicationContext(), "Increase your phone's ringing Volume if low.", Toast.LENGTH_LONG).show();
    }

}
...