一:Android 7.0权限及以上【拍照+裁剪+打开相册+显示视图圆形图片并上传服务器】总结

一:图片展示

   

 二:activity_personal_center.xml

<LinearLayout
    android:id="@+id/information_head"
    android:layout_width="match_parent"
    android:layout_height="46dp"
    android:background="@drawable/abc_rectangle_white"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:paddingStart="@dimen/between_10"
    android:paddingEnd="@dimen/between_10">

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="头像"
        android:textColor="@color/dark_text_33" />

    <ImageView
        android:id="@+id/iv_information_head"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginEnd="@dimen/between_10" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="3dp"
        android:background="@mipmap/ic_arrow_right" />

</LinearLayout>

 三:pop_head_portrait.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/ll_pop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="@dimen/intv_15"
        android:layout_marginEnd="@dimen/intv_15"
        android:orientation="vertical">

        <Button
            android:id="@+id/icon_btn_camera"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/shape_head_album"
            android:text="拍照"
            android:textColor="@color/dark_text_2a" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/light_text_ff" />

        <Button
            android:id="@+id/icon_btn_select"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/shape_head_photograph"
            android:text="从相册选择"
            android:textColor="@color/dark_text_2a" />

        <Button
            android:id="@+id/icon_btn_cancel"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="15dp"
            android:background="@drawable/shape_head_cancel"
            android:text="取消"
            android:textColor="@color/dark_text_2a" />
    </LinearLayout>
</RelativeLayout>

 四:PersonalCenterActivity

@OnClick(R.id.information_head)
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.information_head:
            popShowFaces();
            break;
 }
}

private void popShowFaces() {
    View mView = LayoutInflater.from(this).inflate(R.layout.pop_head_portrait, null, false);

    PopupWindow mPopupWindow = new PopupWindow(mView, ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);

    Button icon_btn_camera = (Button) mView.findViewById(R.id.icon_btn_camera);
    Button icon_btn_select = (Button) mView.findViewById(R.id.icon_btn_select);
    Button icon_btn_cancel = (Button) mView.findViewById(R.id.icon_btn_cancel);
    icon_btn_camera.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            //拍照处理
            mPopupWindow.dismiss();
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                return;
            }

            avatarName = Configs.HEADPORTRAIT.IMAGE_FILE_NAME + System.currentTimeMillis() + ".jpg";
            avatarUrl = new File(rootFile, Configs.HEADPORTRAIT.IMAGE_FILE_NAME + 
                                                                System.currentTimeMillis() + ".jpg");
            //是否有文件,没有就创建
            if (!rootFile.exists()) rootFile.mkdirs();

            //跳转到调用系统相机
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            //判断版本 如果在Android7.0以上,使用FileProvider获取Uri
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri contentUri = FileProvider.getUriForFile
                                    (PersonalCenterActivity.this, getPackageName(), avatarUrl);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);

            } else {
                //否则使用Uri.fromFile(file)方法获取Uri
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(avatarUrl));
            }
             //授予临时权限
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | 
                                           Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
         ActivityCompat.requestPermissions(PersonalCenterActivity.this, new String[] 
                 {Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);   
        startActivityForResult(intent, Configs.HEADPORTRAIT.REQUEST_IMAGE_CAPTURE);
        }
    });
    icon_btn_select.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //相册处理
            mPopupWindow.dismiss();
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            // 判断系统中是否有处理该 Intent 的 Activity
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivityForResult(intent, Configs.HEADPORTRAIT.REQUEST_IMAGE_GET);
            } else {
                Toast.makeText(PersonalCenterActivity.this, "未找到图片查看器", Toast.LENGTH_SHORT).show();
            }
        }
    });
    icon_btn_cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //取消
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(Environment.getExternalStorageDirectory(),                      Configs.HEADPORTRAIT.IMAGE_FILE_NAME)));
            startActivityForResult(intent, Configs.HEADPORTRAIT.REQUEST_IMAGE_CAPTURE);
            mPopupWindow.dismiss();
        }
    });

    mPopupWindow.setFocusable(true);
    mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

    mPopupWindow.setOutsideTouchable(true);
    mPopupWindow.showAtLocation(mView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

    //设置PopWindow背景颜色。
    WindowManager.LayoutParams lp = getWindow().getAttributes();
    lp.alpha = 0.7f;
    getWindow().setAttributes(lp);

    //给Pop设置监听,取消Popt弹出时的背景颜色。
    mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

        @Override
        public void onDismiss() {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.alpha = 1f;
            getWindow().setAttributes(lp);
        }
    });
    mView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int height = mView.findViewById(R.id.ll_pop).getTop();
            int y = (int) event.getY();
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (y < height) {
                    mPopupWindow.dismiss();
                }
            }
            return true;
        }
    });
}

//处理点击回调的监听事件
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // 回调成功
    if (resultCode == RESULT_OK) {
        switch (requestCode) {
            // 小图切割
            case Configs.HEADPORTRAIT.REQUEST_SMALL_IMAGE_CUTTING:
                if (data != null) {
                    saveImage(avatarUrl.getAbsolutePath());
                    ivInformationHead.setImageBitmap(BitmapFactory.decodeFile(avatarUrl.getAbsolutePath()));
                }
                break;
            // 相册选取
            case Configs.HEADPORTRAIT.REQUEST_IMAGE_GET:
                try {
                    cropPhoto(data.getData());
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
                break;
            // 拍照
            case Configs.HEADPORTRAIT.REQUEST_IMAGE_CAPTURE:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    Uri contentUri = FileProvider.getUriForFile(
                                           PersonalCenterActivity.this, getPackageName(), avatarUrl);
                    cropPhoto(contentUri);
                } else {
                    cropPhoto(Uri.fromFile(avatarUrl));
                }
                break;
        }
    }
}

//裁剪
private void cropPhoto(Uri uri) {
    File cropFile = new File(rootFile, avatarName);
    if (!rootFile.exists()) rootFile.mkdirs();
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    intent.putExtra("outputX", 300);
    intent.putExtra("outputY", 300);
    intent.putExtra("return-data", false);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropFile));
    intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
    intent.putExtra("noFaceDetection", true);
    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivityForResult(intent, Configs.HEADPORTRAIT.REQUEST_SMALL_IMAGE_CUTTING);
}

// 保存图片
private void saveImage(String path) {
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        return;
    }
    Bitmap bitmap = BitmapFactory.decodeFile(path);

    FileOutputStream outputStream = null;
    try {
        outputStream = new FileOutputStream(avatarUrl);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    //在视图中显示图片(原图显示)
    Glide.with(this).load(bitmap).apply(RequestOptions.bitmapTransform(
                                                         new  CircleCrop())).into(ivInformationHead);

    RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), avatarUrl);
    MultipartBody.Part body = MultipartBody.Part.createFormData(
                                                  "head_portrait", avatarUrl.getName(), requestFile);
    Capricornus
            .remoteApi()
             //上传图片到服务器的接口
            .avatar_upload(body)
            .enqueue(new TCallback<Void>() {
                @Override
                public void done(Void response) {
                    showTip("头像更新成功!");
                }
            });
}

 五:class Capricornus

import com.dintech.app.nameplate.api.req.LoggerInterceptor;
import com.dintech.app.nameplate.api.req.OauthInterceptor;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public final class Capricornus {

    private static Capricornus remoteApi;
    private final Retrofit retrofit;

    private Capricornus() {
        this.retrofit = new Retrofit.Builder()
                .baseUrl("http://xxx.xx.x.xx/xxx/xx/xxx/")
//                .baseUrl("http://xxx.xx.x.xxx:8000/xxx/xxx/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(new OkHttpClient.Builder().addInterceptor(new OauthInterceptor()).addInterceptor(new com.dintech.app.nameplate.api.LoggerInterceptor().setLevel(com.dintech.app.nameplate.api.LoggerInterceptor.Level.BODY)).addInterceptor(LoggerInterceptor.newInterceptor()).build())
                .build();
    }

    public static Api remoteApi() {
        if (remoteApi == null)
            synchronized (Capricornus.class) {
                if (remoteApi == null) remoteApi = new Capricornus();
            }
        return remoteApi.retrofit.create(Api.class);
    }
}

六:class Configs

public final class Configs {

public interface HEADPORTRAIT {
    int    REQUEST_IMAGE_GET           = 0;
    int    REQUEST_IMAGE_CAPTURE       = 1;
    int    REQUEST_SMALL_IMAGE_CUTTING = 2;
    String IMAGE_FILE_NAME             = "u_avatar_";
 }
}

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值