android 拍照并压缩照片

获取存储图片文件对象

public File getPhotoFile(Crime crime) {

        //获取存放图片文件的路径
        File extrenalFilesDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if(extrenalFilesDir == null) {
            return null;
        }

        //如果存在路径,那么获取File对象,为crime.getPhotoFilename()对象
        return new File(extrenalFilesDir, crime.getPhotoFilename());
    }

启动相机

<span style="white-space:pre">	</span>mPhotoFile = getPhotoFile(crime);
<span style="white-space:pre">	</span>//打开相机的Intent
        final Intent captureImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //当前存储的路径不为空并且存在能够接收当前intent的应用
        boolean canTakePhoto = mPhotoFile != null && captureImage.resolveActivity(packageManager) != null;
        if(canTakePhoto) {
            //获取文件的Uri
            Uri uri = Uri.fromFile(mPhotoFile);
            //指定图片的储存位置
            captureImage.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        mPhotoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(captureImage, REQUEST_PHOTO);
            }
        });


压缩图片同时将图片显示在设备上

mPhotoView = (ImageView) view.findViewById(R.id.crime_photo);
if(mPhotoView == null || !mPhotoFile.exists()) {
            mPhotoView.setImageDrawable(null);
        } else {
            Bitmap bitmap = PictureUtils.getScaledBitmap(mPhotoFile.getPath(), getActivity());
            mPhotoView.setImageBitmap(bitmap);
        }

PictureUtiles.getScaledBitmap()方法

    //获取屏幕尺寸
    public static Bitmap getScaledBitmap(String path, Activity activity) {
        Point size = new Point();
        activity.getWindowManager().getDefaultDisplay().getSize(size);
        return getScaledBitmap(path, size.x, size.y);
    }

    //destWidth destHeight对比的高宽
    public static Bitmap getScaledBitmap(String path, int destWidth, int destHeight) {

        //创建图片处理条件的对象
        BitmapFactory.Options options = new BitmapFactory.Options();

        //设置该属性为true,不加载图片到内存,只返回图片的宽高到options中。
        options.inJustDecodeBounds = true;

        //加载获取图片的宽高
        BitmapFactory.decodeFile(path, options);

        //当前图片高宽
        float srcWidth = options.outWidth;
        float srcHeight = options.outHeight;

        int inSampleSize = 1;
        if(srcHeight > destHeight || srcWidth > destWidth) {
            if(srcWidth > srcHeight) {
                inSampleSize = Math.round(srcHeight / destHeight);
            } else {
                inSampleSize = Math.round(srcWidth / destWidth);
            }
        }

        //缩放比例
        options = new BitmapFactory.Options();
        options.inSampleSize = inSampleSize;

        return BitmapFactory.decodeFile(path, options);
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值