Android 调用相册或相机选择图片


    /**
     * 裁剪
     *
     * @param
     */
    protected void cropPic(File file) {
        if (!file.exists()) {
            Toast.makeText(this, "图片不存在", 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) {
//        fileList.add(new File(new URI(uri.toString())));
        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);

    }

    /**
     * 从相册中获取图片
     */
    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(MediaStore.ACTION_IMAGE_CAPTURE);

            // 图片路径?照相后图片要存储的位置
            picPath = getPicName();
            // 指定输出路径
//            file_image = new File(picPath);

            photouri = Uri.fromFile(new File(picPath));
            getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, photouri);
            getImageByCamera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            startActivityForResult(getImageByCamera, REQUEST_CODE_CAPTURE_CAMEIA);
        } else {
            Toast.makeText(this, "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }

    // 得到图片名称
    public String getPicName() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Date date = new Date();
            return Environment.getExternalStorageDirectory().toString() + "/" + date.getTime() + ".png";
        }
        return null;
    }
    private boolean boolean_delete;
    @Override
    public void onActivityResult(final int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 判断请求码
        switch (requestCode) {
            case REQUEST_CODE_PICK_IMAGE:// 从相册中获取数据后返回
                boolean_delete = false;
                if (data == null) {
                    Toast.makeText(this, "未选择图片", Toast.LENGTH_SHORT).show();
                    return;
                }
                uri = data.getData();
//                Log.d("TAG", "相册中返回"+uri);
                // 进行裁剪
                cropPic(uri);
                break;
            case REQUEST_CODE_CAPTURE_CAMEIA:// 从相机中获取后返回
                boolean_delete = true;
//                myMsgUserImage.setImageURI(photouri);
                cropPic(new File(picPath));
                break;
            case REQUEST_CODE_CROP:// 裁剪完成后的返回
                if (boolean_delete) {
                    picutil.deletePic(picPath);// 裁剪完成后删除原图
                }
                // 拿到剪切数据
                Bitmap bmap = data.getParcelableExtra("data");// 裁剪过后的bitmap
                // 压缩
                yasuo_bitmap = picutil.compressImage(bmap);

                if (boolean_delete) {
                    // 展示到了图片上
//                    mainDrawerUserImage.setImageURI(photouri);
                    Glide.with(this).load(photouri).transform(new GlideCircleTransform(this)).into(mainDrawerUserImage);
                } else {
                    mainDrawerUserImage.setImageURI(uri);
//                    Glide.with(this).load(uri).transform(new GlideCircleTransform(this)).into(mainDrawerUserImage);
                }
                sendMultipart();
                break;
            case 10001:

                break;
            default:
                break;
        }
    }
//    }


    boolean saveBitmap2file(Bitmap bmp) {
        Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG;
        int quality = 100;
        OutputStream stream = null;
        try {
            yasuo_picname = getPicName();

            stream = new FileOutputStream(yasuo_picname);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bmp.compress(format, quality, stream);

    }

获得图片后上传到服务器


 /**
     * 上传文件及参数
     */
    private void sendMultipart() {
        File sdcache = getExternalCacheDir();
        int cacheSize = 1 * 1024 * 1024;
        //设置超时时间及缓存
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
        OkHttpClient mOkHttpClient = builder.build();
        MultipartBody.Builder mbody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        final String user_id = (String) SpUtil.get(this, "user_id", "");
        if (user_id.length() < 1) {
            Toast.makeText(this, "无用户登录,无法提交到服务器", Toast.LENGTH_SHORT).show();
            return;
        }
        mbody.addFormDataPart("user_id", user_id);
        int i = 0;
        saveBitmap2file(yasuo_bitmap);
        if (boolean_delete) {
            mbody.addFormDataPart("avatar[]", picPath, RequestBody.create(media_type_png, new File(yasuo_picname)));
        } else {
            String[] imgs = {MediaStore.Images.Media.DATA};//将图片URI转换成存储路径
            Cursor cursor = this.managedQuery(uri, imgs, null, null, null);
            int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String img_url = cursor.getString(index);
            mbody.addFormDataPart("avatar[]", img_url, RequestBody.create(media_type_png, new File(yasuo_picname)));
        }
        RequestBody requestBody = mbody.build();
        Request request = new Request.Builder()
                .url("自己的url")//url
                .post(requestBody)
                .build();
//        dialog_net.show();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("tag", e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    final JSONObject obj = new JSONObject(response.body().string());
			//上传成功后进行的处理
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Toast.makeText(MainActivity.this, obj.get("msg").toString(), Toast.LENGTH_SHORT).show();
                             
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });


    }











你可能感兴趣的:(Android)