文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

android Camera自动拍照、自动对焦并获取指定大小图片

2022-06-06 13:48

关注

1.首先android6.0以上版本要动态申请相机和文件读写权限
2.废话不啰嗦,上代码:


public class DistinguishActivity extends BaseActivity implements SurfaceHolder.Callback, Camera.PictureCallback {
    private ImageView iv_ivPhoto;
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private Camera camera;
    List unGrantedPermissions;
    private static final String[] MANDATORY_PERMISSIONS = {
            "android.permission.CAMERA",
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private String localImgPath;
    private LinearLayout guide_layout;
    private TextView btn_preview;
    private IPointToReadClient client;
    private boolean isAuthorizatoned = false;
    private final int TAKE_PICTURE = 0xa1;
    private boolean camaraPouse = false;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case TAKE_PICTURE:
                    takePicture();
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_distinguish);
        initViews();
        checkPermissions();
    }
    @Override
    protected void onResume() {
        super.onResume();
        if (camaraPouse) {
            initCamera();
        }
    }
    private void checkPermissions() {
        unGrantedPermissions = new ArrayList();
        for (String permission : MANDATORY_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                unGrantedPermissions.add(permission);
            }
        }
        if (unGrantedPermissions.size() == 0) {//已经获得了所有权限
            initCamera();
        } else {//部分权限未获得,重新请求获取权限
            String[] array = new String[unGrantedPermissions.size()];
            ActivityCompat.requestPermissions(this, unGrantedPermissions.toArray(array), 0);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        unGrantedPermissions.clear();
        for (int i = 0; i  0) {
            for (String permission : unGrantedPermissions) {
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                    Toast.makeText(this, "权限" + permission + "被拒绝", Toast.LENGTH_SHORT).show();
                    finish();
                } else ActivityCompat.requestPermissions(this, new String[]{permission}, 0);
            }
        } else {
            initCamera();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        camera.release();
        camera = null;
        handler.removeMessages(TAKE_PICTURE);
    }
    private void initViews() {
        surfaceView = (SurfaceView) findViewById(R.id.iv_surfaceview);
        iv_ivPhoto = (ImageView) findViewById(R.id.iv_Photo);
        btn_close = (ImageView) findViewById(R.id.btn_close);
        btn_preview = (TextView) findViewById(R.id.btn_preview);
        guide_layout = (LinearLayout) findViewById(R.id.guide_layout);
        btn_preview.setOnClickListener(this);
		showCamera();
    }
    private void initCamera() {
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.setFormat(PixelFormat.TRANSPARENT);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surfaceHolder.setKeepScreenOn(true);//屏幕常亮
        surfaceHolder.addCallback(this);
        handler.sendEmptyMessageDelayed(TAKE_PICTURE, 1000);//2秒后自动拍照
    }
    private void takePicture() {
        if (null != camera && null != client) {
            camera.takePicture(null, null, null, DistinguishActivity.this);
            Toast.makeText(DistinguishActivity.this,"=========拍照========",Toast.LENGTH_SHORT).show();
            LogUtils.debugInfo("takePicture------------执行了拍照------------");
        }
    }
    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        int cameraNums = Camera.getNumberOfCameras();
        LogUtils.debugInfo("surfaceCreated------------" + cameraNums + "---------------");
        try {
            camera = Camera.open(cameraNums - 1);
            camera.setPreviewDisplay(surfaceHolder);
            Camera.Parameters parameters = camera.getParameters();
            List sizeList = parameters.getSupportedPictureSizes();
            int bestSize = 0;
            for (Camera.Size size : sizeList) {
                if (size.width == size.height) {
                    bestSize = size.width;
                }
                LogUtils.debugInfo("系统支持的尺寸-----------------------size.width=" + size.width + ";size.height=" + size.height);
            }
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);//1连续对焦
            if (bestSize == 0) {
                parameters.setPictureSize(2976, 2976);//这个尺寸最接近1440*1440
            } else {
                parameters.setPictureSize(bestSize, bestSize);
            }
            if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
                parameters.set("orientation", "portrait");
                camera.setDisplayOrientation(90);
                parameters.setRotation(90);
            }
            List colorEffects = parameters.getSupportedColorEffects();
            Iterator cei = colorEffects.iterator();
            while (cei.hasNext()) {
                String currentEffect = cei.next();
                if (currentEffect.equals(Camera.Parameters.EFFECT_SOLARIZE)) {
                    parameters
                            .setColorEffect(Camera.Parameters.EFFECT_SOLARIZE);
                    break;
                }
            }
            camera.setParameters(parameters);
            camera.startPreview();
            camera.cancelAutoFocus();// 2如果要实现连续的自动对焦,这一句必须加上
        } catch (Exception e) {
            // TODO Auto-generated catch block
            LogUtils.debugInfo("Camera.open------------Exception------------" + e.getMessage());
            Toast.makeText(DistinguishActivity.this, "相机打开失败", Toast.LENGTH_SHORT).show();
            camera.release();
            finish();
        }
    }
    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
//        //实现自动对焦
        camera.autoFocus(new Camera.AutoFocusCallback() {
            @Override
            public void onAutoFocus(boolean success, Camera camera) {
                if (success) {
                    camera.startPreview();
                    camera.cancelAutoFocus();//只有加上了这一句,才会自动对焦。
                }
            }
        });
    }
    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        try {
            camera.stopPreview();
            camera.release();
        }catch (RuntimeException e){
            LogUtils.debugInfo("surfaceDestroyed------------------------RuntimeException="+e.getMessage());
        }
    }
    @Override
    public void onPictureTaken(byte[] bytes, Camera mcamera) {
        LogUtils.debugInfo("onPictureTaken------------------------");
        mcamera.startPreview();
        BitmapFactory.Options options = new BitmapFactory.Options();
        final Bitmap bitmap = getPicFromBytes(bytes, options);//byte转为bitmap原图
        final Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 1440, 1440, true);//原图压缩为指定尺寸
        final Bitmap result = setMatrix(scaledBitmap);//改变镜像
        new Thread(new Runnable() {
            @Override
            public void run() {
                //保存到本地
                saveImageToGallery(result);
                // 发起网络请求,上传图片到服务器
handler.sendEmptyMessageDelayed(TAKE_PICTURE, 50);//1秒后自动拍照
            }
        }).start();
    }
    
    private Bitmap getPicFromBytes(byte[] bytes,
                                         BitmapFactory.Options opts) {
        if (bytes != null)
            if (opts != null)
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
                        opts);
            else
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return null;
    }
    
    private Bitmap setMatrix(Bitmap bmpPreview) {
        Bitmap bitmap = null;
        Matrix m = new Matrix();
        m.postScale(-1, 1); // 镜像水平翻转
        bitmap = Bitmap.createBitmap(bmpPreview, 0, 0, bmpPreview.getWidth(), bmpPreview.getHeight(), m, true);
        return bitmap;
    }
    public int saveImageToGallery(Bitmap bmp) {
        //生成路径
        String root = Environment.getExternalStorageDirectory().getAbsolutePath();
        String dirName = "FingerReadingPhoto";
        File appDir = new File(root, dirName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        String fileName = "TestPhoto.png";
        localImgPath = appDir + "/" + fileName;
        //获取文件
        File file = new File(appDir, fileName);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            //通知系统相册刷新
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                    Uri.fromFile(new File(file.getPath()))));
            return 2;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return -1;
    }
    private void hideCamera() {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) surfaceView.getLayoutParams();
        params.width = 1;
        params.height = 1;
        surfaceView.setLayoutParams(params);
    }
    private void showCamera() {
        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        int widthPixels = outMetrics.widthPixels;
        int heightPixels = outMetrics.heightPixels;
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) surfaceView.getLayoutParams();
        params.width = widthPixels;
        params.height = heightPixels;
        surfaceView.setLayoutParams(params);
    }
    public void close(View view) {
        if (action == 0) {
            guide_layout.setVisibility(View.VISIBLE);
            hideCamera();
        } else {
            finish();
        }
    }
}

作者:liaoff


阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-移动开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯