OKhttp上传头像,调用相机相册进行裁剪

MainActivity

package com.example.zer.headuploading;

import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView img_pic;
    //我们不论是照相还是从图库选择都需要用到一个方法onActivityResult,所以我们要对请求码作出相应的设置
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESIZE_REQUEST_CODE = 2;
    private static final String IMAGE_FILE_NAME = "header.jpg";
    private File file;
    private PopupWindow mPopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img_pic = findViewById(R.id.img_pic);
        img_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopwindow();
            }
        });
    }

    private void showPopwindow() {
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.popwindow, null);
        mPopupWindow = new PopupWindow(view, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setContentView(view);
        TextView text_xiang = view.findViewById(R.id.text_xiang);
        TextView text_phono = view.findViewById(R.id.text_phono);
        TextView text_quxiao = view.findViewById(R.id.text_quxiao);
        text_xiang.setOnClickListener(this);
        text_phono.setOnClickListener(this);
        text_quxiao.setOnClickListener(this);
        //显示PopupWindow
        mPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.text_xiang:
                if (isSdcardExisting()) {
                    Intent cameraIntent = new Intent(
                            "android.media.action.IMAGE_CAPTURE");
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri());
                    cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
                } else {
                    Toast.makeText(view.getContext(), "请插入sd卡", Toast.LENGTH_LONG)
                            .show();
                }
                mPopupWindow.dismiss();
                break;
            case R.id.text_phono:
                Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT);
                intent1.addCategory(Intent.CATEGORY_OPENABLE);
                intent1.setType("image/*");
                startActivityForResult(intent1, IMAGE_REQUEST_CODE);
                mPopupWindow.dismiss();
                break;
            case R.id.text_quxiao:
                mPopupWindow.dismiss();
                break;
        }
    }
    //获取图片的URI
    private Uri getImageUri() {
        file = new File(Environment.getExternalStorageDirectory(),
                IMAGE_FILE_NAME);
        return Uri.fromFile(file);
    }
    /**
     * 判断sd卡是否存在
     *
     * @return
     */
    private boolean isSdcardExisting() {
        final String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
    //该方法是用于放回相应结果的
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode==RESULT_OK){
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    resizeImage(data.getData());
                    break;
                case CAMERA_REQUEST_CODE:
                    if(isSdcardExisting()){
                        resizeImage(getImageUri());
                    }else{
                        Toast.makeText(MainActivity.this, "未找到存储卡,无法存储照片!",
                                Toast.LENGTH_LONG).show();
                    }
                    break;
                case RESIZE_REQUEST_CODE:
                    if (data != null) {
                        showResizeImage(data);
                    }
                    break;

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    /**
     * 展示头像
     * @param data
     */
    private void showResizeImage(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(photo);
            img_pic.setImageDrawable(drawable);
            headUploding();
        }
    }
    /**
     * 对图片进行处理
     * @param uri
     */
    private void resizeImage(Uri uri) {
        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", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESIZE_REQUEST_CODE);
    }
    public void headUploding(){
        //创建OkHttpClient请求对象

        OkHttpClient okHttpClient = new OkHttpClient();
        //创建RequestBody 封装file参数
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        //创建RequestBody 设置类型等
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", file.getName(), fileBody).build();
        //创建Request
        Request request = new Request.Builder().url("https://www.zhaoapi.cn/file/upload?uid=14646").post(requestBody).build();

        //得到Call
        okhttp3.Call call = okHttpClient.newCall(request);
        //执行请求
        call.enqueue(new okhttp3.Callback() {


            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                Log.d("成功", "onResponse: 开心");
            }
        });

    }
}

你可能感兴趣的:(Android)