android 相机图库调用以及裁剪

相机调用

private void selectPicFromCamera() {
        mOutputFile = getPicFile(getActivity());
        Log.e(TAG,
                "selectPicFromGallery : " + mOutputFile.getPath() + "  "
                        + mOutputFile.exists());
        Uri pcUri = Uri.fromFile(mOutputFile);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, pcUri); // 指定图片输出地址
        if (mCrop) {
            // 头像要用到裁剪
            startActivityForResult(intent, REQUEST_CODE_CAREMA_CROP);
        }
        else {
            // 相册不需要用到裁剪
            startActivityForResult(intent, REQUEST_CODE_CAREMA);
        }
    }

相册调用

private void selectPicFromGallery() {
        mOutputFile = getPicFile(getActivity());
        Log.e(TAG,
                "selectPicFromCamera : " + mOutputFile.getPath() + "  "
                        + mOutputFile.exists());
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        if (mCrop) {
            // 头像需要用到裁剪
            startActivityForResult(intent, REQUEST_CODE_GALLERY_CROP);
        }
        else {
            // 相册不需要用到裁剪
            startActivityForResult(intent, REQUEST_CODE_GALLERY);
        }
    }

裁剪

private void startCropPicture(File cropPicFile) {
        if (cropPicFile != null && cropPicFile.exists()) {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(cropPicFile.getPath(), options);
            Log.i("++++2222----DecodeBitmap + " + cropPicFile.getPath(), options.outWidth + "  " + options.outHeight + "  "
                    + options.inSampleSize);
            options.inJustDecodeBounds = false;
            Intent caremaCropintent = new Intent("com.android.camera.action.CROP");// 剪裁
            caremaCropintent.setDataAndType(Uri.fromFile(cropPicFile), "image/*");
            caremaCropintent.putExtra("crop", "true");
            // 设置宽高比例
            caremaCropintent.putExtra("aspectX", 1);
            caremaCropintent.putExtra("aspectY", 1);
            // 设置裁剪图片宽高
            caremaCropintent.putExtra("outputX", mOutputX);
            caremaCropintent.putExtra("outputY", mOutputY);
            caremaCropintent.putExtra("return-data", false);
            caremaCropintent.putExtra("noFaceDetection", false); // no face detection
            caremaCropintent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mOutputFile));
            caremaCropintent.putExtra("outputFormat",
                    Bitmap.CompressFormat.JPEG.toString());
            startActivityForResult(caremaCropintent, REQUEST_CODE_SELECTED); // 设置裁剪参数显示图片至ImageView
        }
        
    }

图片缩放

public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth,
            int reqHeight) {
        // 原始图片的宽高
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (reqWidth <= 0 || reqHeight <= 0 || width <= 0 || height <= 0) {
            return inSampleSize;
        }
        
        if (height > reqHeight || width > reqWidth) {
            
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            
            // 在保证解析出的bitmap宽高分别大于目标尺寸宽高的前提下,取可能的inSampleSize的最大值
            while ((halfHeight / inSampleSize) >= reqHeight
                    && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }
        Log.i("DecodeBitmap", options.outWidth + "  " + options.outHeight + "  "
                + options.inSampleSize);
        
        return inSampleSize;
    }
    
    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
            int reqWidth, int reqHeight, Config config) {
        
        // 首先设置 inJustDecodeBounds=true 来获取图片尺寸
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
        
        // 计算 inSampleSize 的值
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        if (config != null) {
            options.inPreferredConfig = config;
        }
        
        // 根据计算出的 inSampleSize 来解码图片生成Bitmap
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }
    
    public static Bitmap decodeSampledBitmapFromFile(String filePath, int reqWidth,
            int reqHeight, Config config) {
        
        // 首先设置 inJustDecodeBounds=true 来获取图片尺寸
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        
        // 计算 inSampleSize 的值
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        if (config != null) {
            options.inPreferredConfig = config;
        }
        
        Log.i("DecodeBitmap", options.outWidth + "  " + options.outHeight + "  "
                + options.inSampleSize);
        
        // 根据计算出的 inSampleSize 来解码图片生成Bitmap
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

图片文件压缩

public static void saveBitmapToFileWithCompress(String picFilePath, Bitmap bitmap) {
        File photoFile = new File(picFilePath); // 在指定路径下创建文件
        FileOutputStream fileOutputStream = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int scale = 100;
        double baosSize = 0;
        try {
            fileOutputStream = new FileOutputStream(photoFile);
            if (bitmap != null) {
                if (bitmap.compress(Bitmap.CompressFormat.JPEG, scale, baos)) {
                    baosSize = baos.toByteArray().length / 1024;
                    scale -= 20;
                    while (baosSize > 500 && scale > 0) {
                        baos.reset();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, scale, baos);
                        baosSize = baos.toByteArray().length / 1024;
                        scale -= 20;
                    }
                    // 缩放后的数据写入到文件中
                    baos.writeTo(fileOutputStream);
                    fileOutputStream.flush();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            photoFile.delete();
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


SelectPictureManager封装整个操作

package com.qingqing.base;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.qingqing.base.view.dialog.ActionSheetDialog;
import com.qingqing.base.view.dialog.ActionSheetDialog.OnSheetItemClickListener;
import com.qingqing.base.view.dialog.ActionSheetDialog.SheetItemColor;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.Config;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;

public class SelectPictureManager {
    
    private static final String TAG = "SelectPictureManager";
    
    private static final int REQUEST_CODE_CAREMA = 10001;
    private static final int REQUEST_CODE_CAREMA_CROP = 10002;
    private static final int REQUEST_CODE_GALLERY = 10003;
    private static final int REQUEST_CODE_GALLERY_CROP = 10004;
    private static final int REQUEST_CODE_SELECTED = 10005;
    
    private Activity mActivity;
    private Fragment mFragment;
    
    private boolean mCrop;
    
    private SelectPicListerner mSelectPicListerner;
    
    private int mOutputX;
    private int mOutputY;
    
    private File mOutputFile;
    
    private final boolean mIsFragment;
    
    private int mKey;
    
    public SelectPictureManager(Activity activity) {
        mActivity = activity;
        mIsFragment = false;
    }
    
    public SelectPictureManager(Fragment fragment) {
        mFragment = fragment;
        mIsFragment = true;
    }
    
    public void setSelectPicListerner(SelectPicListerner l) {
        mSelectPicListerner = l;
    }
    
    /** 不裁剪 ,保持原图 */
    public void startSelectPicture() {
        startSelectPicture(-1, 0, 0);
    }
    
    /** 不裁剪 ,保持原图 */
    public void startSelectPicture(int key) {
        startSelectPicture(key, 0, 0);
    }
    
    /** 不裁剪 outputX > 0 and outputY > 0 输出的图按照outputX和outputY来缩放 */
    public void startSelectPicture(int outputX, int outputY) {
        startSelectPicture(-1, false, outputX, outputY);
    }
    
    /** 不裁剪 outputX > 0 and outputY > 0 输出的图按照outputX和outputY来缩放 */
    public void startSelectPicture(int key, int outputX, int outputY) {
        startSelectPicture(key, false, outputX, outputY);
    }
    
    public void startSelectPicture(boolean crop, int outputX, int outputY) {
        startSelectPicture(-1, crop, outputX, outputY);
    }
    
    public void startSelectPicture(int key, boolean crop, int outputX, int outputY) {
        mKey = key;
        mCrop = crop;
        mOutputX = outputX;
        mOutputY = outputY;
        final Activity activity = getActivity();
        if (activity != null) {
            new ActionSheetDialog(activity)
                    .builder()
                    .setCancelable(true)
                    .setCanceledOnTouchOutside(true)
                    .addSheetItem("拍照", SheetItemColor.Gray,
                            new OnSheetItemClickListener() {
                                
                                @Override
                                public void onClick(int which) {
                                    selectPicFromCamera();
                                }
                            })
                    .addSheetItem("去相册选择", SheetItemColor.Gray,
                            new OnSheetItemClickListener() {
                                
                                @Override
                                public void onClick(int which) {
                                    selectPicFromGallery();
                                }
                            }).show();
            
        }
    }
    
    private void startCropPicture(File cropPicFile) {
        if (cropPicFile != null && cropPicFile.exists()) {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(cropPicFile.getPath(), options);
            Log.i("++++2222----DecodeBitmap + " + cropPicFile.getPath(), options.outWidth + "  " + options.outHeight + "  "
                    + options.inSampleSize);
            options.inJustDecodeBounds = false;
            Intent caremaCropintent = new Intent("com.android.camera.action.CROP");// 剪裁
            caremaCropintent.setDataAndType(Uri.fromFile(cropPicFile), "image/*");
            caremaCropintent.putExtra("crop", "true");
            // 设置宽高比例
            caremaCropintent.putExtra("aspectX", 1);
            caremaCropintent.putExtra("aspectY", 1);
            // 设置裁剪图片宽高
            caremaCropintent.putExtra("outputX", mOutputX);
            caremaCropintent.putExtra("outputY", mOutputY);
            caremaCropintent.putExtra("return-data", false);
            caremaCropintent.putExtra("noFaceDetection", false); // no face detection
            caremaCropintent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mOutputFile));
            caremaCropintent.putExtra("outputFormat",
                    Bitmap.CompressFormat.JPEG.toString());
            startActivityForResult(caremaCropintent, REQUEST_CODE_SELECTED); // 设置裁剪参数显示图片至ImageView
        }
        
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e(TAG, "requestCode = " + requestCode + "  |   resultCode = " + resultCode);
        final Activity activity = mIsFragment ? mFragment.getActivity() : mActivity;
        if (activity == null) {
            return;
        }
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_GALLERY:
                File selectedPicFile = getSelectedPicFileFromGallery(data);
                if (mOutputX > 0 && mOutputY > 0) {
                    if (selectedPicFile != null && selectedPicFile.exists()
                            && mOutputFile != null && mOutputFile.exists()) {
                        Bitmap b = decodeSampledBitmapFromFile(selectedPicFile.getPath(),
                                mOutputX, mOutputY, Config.ARGB_4444);
                        Log.i(TAG, "save before" + selectedPicFile.length()
                                / (double) 1024);
                        saveBitmapToFileWithCompress(mOutputFile.getPath(), b);
                        if (b != null && !b.isRecycled()) {
                            b.recycle();
                        }
                        Log.i(TAG, "save after" + mOutputFile.length() / (double) 1024);
                        notifyPicSelected(mOutputFile);
                    }
                }
                else {
                    if (selectedPicFile != null && selectedPicFile.exists()) {
                        notifyPicSelected(selectedPicFile);
                    }
                }
                break;
            case REQUEST_CODE_GALLERY_CROP:
                startCropPicture(getSelectedPicFileFromGallery(data));
                break;
            case REQUEST_CODE_CAREMA_CROP:
                startCropPicture(mOutputFile);
                break;
            case REQUEST_CODE_CAREMA:
                if (mOutputX > 0 && mOutputY > 0) {
                    if (mOutputFile != null && mOutputFile.exists()
                            && mOutputFile != null && mOutputFile.exists()) {
                        Bitmap b = decodeSampledBitmapFromFile(mOutputFile.getPath(),
                                mOutputX, mOutputY, Config.ARGB_4444);
                        Log.i(TAG, "save before" + mOutputFile.length() / (double) 1024);
                        saveBitmapToFileWithCompress(mOutputFile.getPath(), b);
                        if (b != null && !b.isRecycled()) {
                            b.recycle();
                        }
                        Log.i(TAG, "save after" + mOutputFile.length() / (double) 1024);
                        notifyPicSelected(mOutputFile);
                    }
                }
                else {
                    if (mOutputFile != null && mOutputFile.exists()) {
                        notifyPicSelected(mOutputFile);
                    }
                }
                break;
            case REQUEST_CODE_SELECTED:
                if (mOutputFile != null && mOutputFile.exists()) {
                    final BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(mOutputFile.getPath(), options);
                    Log.i("++++DecodeBitmap", options.outWidth + "  " + options.outHeight + "  "
                            + options.inSampleSize);
                    options.inJustDecodeBounds = false;
                    notifyPicSelected(mOutputFile);
                }
                break;
            default:
                break;
        }
    }
    
    private Activity getActivity() {
        return mIsFragment ? mFragment.getActivity() : mActivity;
    }
    
    private File getSelectedPicFileFromGallery(Intent data) {
        final Activity activity = getActivity();
        if (data != null && activity != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumns = { MediaStore.Images.Media.DATA };
            Cursor c = activity.getContentResolver().query(selectedImage,
                    filePathColumns, null, null, null);
            String picPath = null;
            if (c.getCount() > 0) {
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePathColumns[0]);
                picPath = c.getString(columnIndex);
                c.close();
            }
            if (!TextUtils.isEmpty(picPath)) {
                File file = new File(picPath);
                return file;
            }
        }
        return null;
    }
    
    private void selectPicFromGallery() {
        mOutputFile = getPicFile(getActivity());
        Log.e(TAG,
                "selectPicFromCamera : " + mOutputFile.getPath() + "  "
                        + mOutputFile.exists());
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        if (mCrop) {
            // 头像需要用到裁剪
            startActivityForResult(intent, REQUEST_CODE_GALLERY_CROP);
        }
        else {
            // 相册不需要用到裁剪
            startActivityForResult(intent, REQUEST_CODE_GALLERY);
        }
    }
    
    private void selectPicFromCamera() {
        mOutputFile = getPicFile(getActivity());
        Log.e(TAG,
                "selectPicFromGallery : " + mOutputFile.getPath() + "  "
                        + mOutputFile.exists());
        Uri pcUri = Uri.fromFile(mOutputFile);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, pcUri); // 指定图片输出地址
        if (mCrop) {
            // 头像要用到裁剪
            startActivityForResult(intent, REQUEST_CODE_CAREMA_CROP);
        }
        else {
            // 相册不需要用到裁剪
            startActivityForResult(intent, REQUEST_CODE_CAREMA);
        }
    }
    
    private void startActivityForResult(Intent intent, int requestCode) {
        if (mIsFragment) {
            mFragment.startActivityForResult(intent, requestCode);
        }
        else {
            mActivity.startActivityForResult(intent, requestCode);
        }
    }
    
    private String getDefaultPicFileName() {
        return System.currentTimeMillis() + ".jpg";
    }
    
    private File getPicFile(Context context) {
        File file = new File(getPicDirs(context), getDefaultPicFileName());
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }
    
    private File getPicDirs(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File dirs = new File(Environment.getExternalStorageDirectory()
                    + "/qingqing/temp_camera/");
            if (!dirs.exists()) {
                dirs.mkdirs();
            }
            return dirs;
        }
        else {
            String filePath = context.getFilesDir().getParent();
            if (!TextUtils.isEmpty(filePath)
                    && filePath.charAt(filePath.length() - 1) == '/') {
                filePath = filePath.substring(0, filePath.length() - 1);
            }
            File dirs = new File(filePath + "/qingqing/temp_camera/");
            if (!dirs.exists()) {
                dirs.mkdirs();
            }
            return dirs;
        }
    }
    
    public void destroy() {
        mActivity = null;
        mFragment = null;
        setSelectPicListerner(null);
    }
    
    private void notifyPicSelected(File outputFile) {
        if (mSelectPicListerner != null) {
            mSelectPicListerner.onPicSelected(mKey, outputFile);
        }
    }
    
    public interface SelectPicListerner {
        public void onPicSelected(int key, File outputFile);
    }
    
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth,
            int reqHeight) {
        // 原始图片的宽高
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (reqWidth <= 0 || reqHeight <= 0 || width <= 0 || height <= 0) {
            return inSampleSize;
        }
        
        if (height > reqHeight || width > reqWidth) {
            
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            
            // 在保证解析出的bitmap宽高分别大于目标尺寸宽高的前提下,取可能的inSampleSize的最大值
            while ((halfHeight / inSampleSize) >= reqHeight
                    && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }
        Log.i("DecodeBitmap", options.outWidth + "  " + options.outHeight + "  "
                + options.inSampleSize);
        
        return inSampleSize;
    }
    
    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
            int reqWidth, int reqHeight, Config config) {
        
        // 首先设置 inJustDecodeBounds=true 来获取图片尺寸
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
        
        // 计算 inSampleSize 的值
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        if (config != null) {
            options.inPreferredConfig = config;
        }
        
        // 根据计算出的 inSampleSize 来解码图片生成Bitmap
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }
    
    public static Bitmap decodeSampledBitmapFromFile(String filePath, int reqWidth,
            int reqHeight, Config config) {
        
        // 首先设置 inJustDecodeBounds=true 来获取图片尺寸
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        
        // 计算 inSampleSize 的值
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        if (config != null) {
            options.inPreferredConfig = config;
        }
        
        Log.i("DecodeBitmap", options.outWidth + "  " + options.outHeight + "  "
                + options.inSampleSize);
        
        // 根据计算出的 inSampleSize 来解码图片生成Bitmap
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }
    
    public static void saveBitmapToFileWithCompress(String picFilePath, Bitmap bitmap) {
        File photoFile = new File(picFilePath); // 在指定路径下创建文件
        FileOutputStream fileOutputStream = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int scale = 100;
        double baosSize = 0;
        try {
            fileOutputStream = new FileOutputStream(photoFile);
            if (bitmap != null) {
                if (bitmap.compress(Bitmap.CompressFormat.JPEG, scale, baos)) {
                    baosSize = baos.toByteArray().length / 1024;
                    scale -= 20;
                    while (baosSize > 500 && scale > 0) {
                        baos.reset();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, scale, baos);
                        baosSize = baos.toByteArray().length / 1024;
                        scale -= 20;
                    }
                    // 缩放后的数据写入到文件中
                    baos.writeTo(fileOutputStream);
                    fileOutputStream.flush();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            photoFile.delete();
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
}

调用流程

相机调用SelectPictureManager


/** 不裁剪 */
mSelectPictureManager.startSelectPicture();
/** 不裁剪  outputX > 0 and outputY > 0*/
mSelectPictureManager。startSelectPicture(int outputX, int outputY);


1.Activity调用
private SelectPictureManager mSelectPictureManager;
在onCreate中
mSelectPictureManager = new SelectPictureManager(this);
mSelectPictureManager.setSelectPicListerner(new SelectPicListerner() {
            
            @Override
            public void onPicSelected(int key, File outputFile) {


            }
        });
在onActivityResult中
if (mSelectPictureManager != null) {
    mSelectPictureManager.onActivityResult(requestCode, resultCode, data);
}


在onDestory中
mSelectPictureManager.destroy();
mSelectPictureManager = null;


2.Fragment调用
private SelectPictureManager mSelectPictureManager;
在onViewCreated中
mSelectPictureManager = new SelectPictureManager(this);
mSelectPictureManager.setSelectPicListerner(new SelectPicListerner() {
            
            @Override
            public void onPicSelected(int key, File outputFile) {


            }
});


在onActivityResult中
if (mSelectPictureManager != null) {
    mSelectPictureManager.onActivityResult(requestCode, resultCode, data);
}


在onDestroyView中
mSelectPictureManager.destroy();
mSelectPictureManager = null;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值