获取手机图片或者打开相机拍照作为头像的案例

PICUtil类:

/**
 * 删除原图
 */
public class PicUtil {
    public void deletePic(String picPath) {
        if (!TextUtils.isEmpty(picPath)) {
            File f = new File(picPath);
            if (f.exists()) {
                f.delete();
            }
        }
    }

    /**
     * 压缩图片 质量压缩法
     *
     * @param image
     * @return
     */
    public Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100 && options > 10) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    /**
     * 保存图片
     *
     * @param photo
     * @param spath
     * @return
     */
    public boolean saveImage(Bitmap photo, String spath) {
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(spath, false));
            photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public String imgToBase64(String imgPath) {

        ByteArrayOutputStream out = null;
        try {
            Bitmap bitmap = null;
            if (imgPath != null && imgPath.length() > 0) {
                bitmap = BitmapFactory.decodeFile(imgPath);
            }
            out = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            byte[] imgBytes = out.toByteArray();
            return Base64.encodeToString(imgBytes, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public String imgToBase64(Bitmap bitmap) {

        ByteArrayOutputStream out = null;
        try {
            out = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            byte[] imgBytes = out.toByteArray();
            return Base64.encodeToString(imgBytes, Base64.DEFAULT);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public String getRealPathFromURI(Context mContext,Uri contentUri) {
        String res = null;
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = mContext.getContentResolver().query(contentUri, proj, null, null, null);
        if(cursor.moveToFirst()){;
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }
MainAcvitity。Java

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_CODE_PICK_IMAGE = 1;
    private static final int REQUEST_CODE_CAPTURE_CAMEIA = 0;
    private static final int REQUEST_CODE_CROP = 2;
    private ImageView iv;
    private AlertDialog.Builder builder;
    private String picPath = "";
    private PicUtil picutil;
    private String str_base64 = "";
    private boolean boolean_delete;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        picutil = new PicUtil();
        iv = (ImageView) findViewById(R.id.iv);
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                createDialog();
            }
        });
    }


    /**
     * 弹出对话框
     */
    public void createDialog() {
        builder = new AlertDialog.Builder(this);
        builder.setTitle("请选择");
        builder.setItems(new String[]{"启动照相机", "打开手机相册", "取消选择"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                switch (arg1) {
                    case 0:
                        getImageFromCamera();
                        break;
                    case 1:
                        getImageFromAlbum();
                        break;
                    default:
                        break;
                }
            }
        });
        builder.create().show();
    }

    /**
     * 从相册中获取图片
     */
    protected void getImageFromAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");// 相片类型
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
    }

    /**
     * 从相机中获取图片
     */
    protected void getImageFromCamera() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {// 如果挂载成功。
            Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
            // 图片路径?照相后图片要存储的位置
            picPath = getPicName();
            // 指定输出路径
            getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(picPath)));
            getImageByCamera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            startActivityForResult(getImageByCamera, REQUEST_CODE_CAPTURE_CAMEIA);
        } else {
            Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 裁剪
     *
     * @param
     */
    protected void cropPic(File file) {
        if (!file.exists()) {
            Toast.makeText(getApplicationContext(), "图片不存在", Toast.LENGTH_LONG).show();
            return;
        }
        Intent intent = new Intent();
        intent.setAction("com.android.camera.action.CROP");
        intent.setDataAndType(Uri.fromFile(file), "image/*");// mUri是已经选择的图片Uri
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);// 输出图片大小
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUEST_CODE_CROP);
    }

    protected void cropPic(Uri uri) {
        Intent intent = new Intent();
        intent.setAction("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");// mUri是已经选择的图片Uri
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);// 输出图片大小
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUEST_CODE_CROP);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show();
            return;
        }
        // 判断请求码
        switch (requestCode) {
            case REQUEST_CODE_PICK_IMAGE:// 从相册中获取数据后返回
                boolean_delete = false;
                Uri uri = data.getData();
                // 进行裁剪
                cropPic(uri);
                break;
            case REQUEST_CODE_CAPTURE_CAMEIA:// 从相机中获取后返回
                boolean_delete = true;
                cropPic(new File(picPath));
                break;
            case REQUEST_CODE_CROP:// 裁剪完成后的返回
                if (boolean_delete) {
                    picutil.deletePic(picPath);// 裁剪完成后删除原图
                }
                // 拿到剪切数据
                Bitmap bmap = data.getParcelableExtra("data");// 裁剪过后的bitmap
                // 压缩
                Bitmap newBmap = picutil.compressImage(bmap);
                // 展示到了图片上
                iv.setImageBitmap(newBmap);
                //如果要上传 bitmap转为二进制流上传,也可以直接保存成为一个file进行上传。
                break;
            default:
                break;
        }
    }

    // 得到图片名称
    public String getPicName() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Date date = new Date();
            return Environment.getExternalStorageDirectory().toString() + "/" + date.getTime() + ".jpg";
        }
        return null;
    }

你可能感兴趣的:(Android)