android 6.0以上版本拍照功能实现

android 6.0及以上版本实现拍照功能的方法

步骤一:创建一个给予权限的Utils,Demo1如下:
private static String[] PERMISSIONS_CAMERA_AND_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA};
public static boolean isCameraPermission(Activity context, int requestCode){
    if (Build.VERSION.SDK_INT >= 23) {
        int storagePermission = ActivityCompat.checkSelfPermission(context,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int cameraPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
        if (storagePermission != PackageManager.PERMISSION_GRANTED || cameraPermission!= PackageManager.PERMISSION_GRANTED ) {
            ActivityCompat.requestPermissions(context, PERMISSIONS_CAMERA_AND_STORAGE,
                    requestCode);
            return false;
        }
    }
    return true;
}

/**
 * 获取bitmap
 *
 * @param filePath
 * @return
 */
public static Bitmap getBitmapByPath(String filePath, int w, int h) {
    FileInputStream fis = null;
    Bitmap bitmap = null;
    try {
        File file = new File(filePath);
        if (file.exists()) {
            fis = new FileInputStream(file);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(filePath, options);
            int originalWidth = options.outWidth;//图片原始宽度
            int originalHeight = options.outHeight;//图片原始高度
            if ((originalWidth == -1) || (originalHeight == -1))
                return null;
            //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
            int be = 1;//be=1表示不缩放
            if (originalWidth > originalHeight && originalWidth > w) {//如果宽度大的话根据宽度固定大小缩放
                be = (int) (originalWidth / w);
            } else if (originalWidth < originalHeight && originalHeight > h) {//如果高度高的话根据宽度固定大小缩放
                be = (int) (originalHeight / h);
            }
            if (be <= 0)
                be = 1;
            options.inJustDecodeBounds = false;
            options.inSampleSize = be;//设置缩放比例
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            bitmap = BitmapFactory.decodeFile(filePath, options);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
    } finally {
        try {
            fis.close();
        } catch (Exception e) {
        }
    }
    //return getBitmapByPath(filePath, bitmapOptions);
    return compressImage(bitmap);
}
/**
 * 质量压缩方法
 *
 * @param image
 * @return
 */
public static Bitmap compressImage(Bitmap image) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
    int options = 90;
    int bytes = baos.toByteArray().length;
    while ((bytes / 1024 > 100) && (options >= 20)) {  //循环判断如果压缩后图片是否大于10kb,大于继续压缩
        baos.reset();//重置baos即清空baos
        options -= 10;//每次都减少10
        //第一个参数 :图片格式 ,第二个参数: 图片质量,100为最高,0为最差  ,第三个参数:保存压缩后的数据的流
        image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
        bytes = baos.toByteArray().length;
    }
    image.recycle();
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
    return bitmap;
}
步骤二:点击拍照方法中调区这个权限Demo1,形如;
if (Demo1.isCameraPermission(ReceiptConfirmActivity.this, 0x007))
                    getCamera();
步骤三:请求权限回调
@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 0x007:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    byCamera();
                } else {
                    Toast.makeText(this, "拍照权限被拒绝", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
步骤四:实现拍照方法
public void getCamera() {
        String savePath = "";
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/camera/";
            File savedir = new File(savePath);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        }
        // 没有挂载SD卡,无法保存文件
        if (savePath == null || "".equals(savePath)) {
            System.out.println("无法保存照片,请检查SD卡是否挂载");
            return;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        //照片命名
        String fileName = timeStamp + ".jpg";
        File out = new File(savePath, fileName);
        Uri uri = Uri.fromFile(out);
        //该照片的绝对路径
        imagePath = savePath + fileName;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, 0x008);
    }
步骤五:显示照片
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 8) {
            if(imagePath!=null && resultCode == RESULT_OK){

                ivGetGoodsPhoto.setImageBitmap(PermissionUtils.getBitmapByPath(imagePath,480,800));
            }
        }
    }

Ok,功能实现!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值