相机上传头像

public class MainActivity extends AppCompatActivity   implements View.OnClickListener{
    FileOutputStream b;
    private PopupWindow popupWindow;
    private View inflate;
    String s = Environment.getExternalStorageDirectory().getParent() + "/li.png";
    File s1 = Environment.getExternalStorageDirectory();
   String FFFF="li.png";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        inflate = View.inflate(this, R.layout.popupwindow, null);
        int widthPixels = getResources().getDisplayMetrics().widthPixels;
        popupWindow = new PopupWindow(widthPixels, 200);
        popupWindow.setContentView(inflate);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.RED));
        popupWindow.setClippingEnabled(true);
        popupWindow.setOutsideTouchable(true);
        Button butt = findViewById(R.id.button1);
        //popupWindow.(findViewById(R.id.button1), );

        butt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.showAtLocation(View.inflate(MainActivity.this,R.layout.activity_main,null), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,0,10);
            }
        });
        Button xiangji = inflate.findViewById(R.id.xiangji);
        Button xiangce = inflate.findViewById(R.id.xiangce);
        xiangce.setOnClickListener(this);
        xiangji.setOnClickListener(this);

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case  R.id.xiangji:
                xiangji();

                break;
            case  R.id.xiangce:
                     //单图
                     Intent intent = new Intent(Intent.ACTION_PICK);
                     intent.setType("image/*");//相片类型
                     startActivityForResult(intent,12);


                     //多图
//                     ImageConfig config = new ImageConfig();
//                     config.minHeight = 400;
//                     config.minWidth = 400;
//                     config.mimeType = new String[]{"image/jpeg", "image/png"}; // 图片类型 image/gif ...
//                    // config.minSize = 1 * 1024 * 1024; // 1Mb 图片大小
//
//                     PhotoPickerIntent intent = new PhotoPickerIntent(UploadActivity.this);
//                     intent.setSelectModel(SelectModel.MULTI); //
//                     intent.setShowCarema(true); // 是否显示拍照
//                     intent.setMaxTotal(6); // 最多选择照片数量,默认为6
//                     intent.setImageConfig(config); // 已选中的照片地址, 用于回显选中状态
//                     startActivityForResult(intent, 11111);
                break;
        }

    }


    public void xiangji(){
        Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(s1, FFFF)));
        startActivityForResult(intentFromCapture, 11);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("dasd","adsadasdasdasdasdsa"+requestCode);
              if (requestCode==11 && resultCode==RESULT_OK){
                  Log.e("dasd","adsadasdasdasdasdsa");
                  //调取裁剪功能
                  Intent intent = new Intent("com.android.camera.action.CROP");
                  intent.setDataAndType(Uri.fromFile(new File(s1, FFFF)),"image/*");
                  // 设置裁剪
                  intent.putExtra("crop", "true");
                  // aspectX aspectY 是宽高的比例
                  intent.putExtra("aspectX", 1);
                  intent.putExtra("aspectY", 1);
                  // outputX outputY 是裁剪图片宽高
                  intent.putExtra("outputX", 300);
                  intent.putExtra("outputY", 300);
                  intent.putExtra("return-data", true);
                  startActivityForResult(intent, 200);
              }
           if (requestCode==200){

               Bitmap data1 = data.getParcelableExtra("data");

               ImageView imageView = new ImageView(this);
               imageView.setImageBitmap(data1);
               File f=new File(Environment.getExternalStorageDirectory(),FFFF);


               Sres getnetjson = Utils.getmInstance().getnetjson("https://www.zhaoapi.cn/");

               //如果用第二种方式上传头像   可以不用写
               RequestBody uidBody = RequestBody.create(MediaType.parse("multipart/form-data"),"12735");

               //f为file路径
               MultipartBody.Part filePart = MultipartBody.Part.createFormData("file",f.getName(),RequestBody.create(
                       MediaType.parse("multipart/form-data"),f
               ));
               //第一种方式上传头像
               Observable upload = getnetjson.upload(uidBody, filePart);
               upload.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
                       .subscribe(new Consumer() {
                           @Override
                           public void accept(FileResultBean fileResultBean) throws Exception {
                               Toast.makeText(MainActivity.this,fileResultBean.getMsg(),Toast.LENGTH_SHORT).show();
                           }
                       }, new Consumer() {
                           @Override
                           public void accept(Throwable throwable) throws Exception {
                               Toast.makeText(MainActivity.this,"失败",Toast.LENGTH_SHORT).show();
                           }
                       });
           }else if(requestCode==12){
            Uri data1 = data.getData();
            //调取裁剪功能
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(data1,"image/*");
            // 设置裁剪
            intent.putExtra("crop", "true");
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // outputX outputY 是裁剪图片宽高
            intent.putExtra("outputX", 300);
            intent.putExtra("outputY", 300);
            intent.putExtra("return-data", true);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(uri, FFFF)));
            startActivityForResult(intent, 200);

        }


   //多图上传
        if (requestCode==11111){


       ArrayList stringArrayListExtra = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);




       ArrayList parts = new ArrayList<>();
       for (String s : stringArrayListExtra) {
            Log.e("path",s);
          // map.put(s, RequestBody.create(MediaType.parse("multipart/form-data"),new File(s)));
           File file = new File(s);
           RequestBody requestBody = MultipartBody.create(MediaType.parse("multipart/form-data"), file);
           MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
           parts.add(part);
       }


       HashMap map = new HashMap<>();
       map.put("uid","10766 ");
       map.put("content","content");
       map.put("token","4543724E4BFB298F78F1C5B6E1A65BF1");
       map.put("source","android");
       map.put("appVersion","101");




       //https://www.zhaoapi.cn/quarter/publishJoke
       Retrofit retrofit=new Retrofit.Builder().
               baseUrl("https://www.zhaoapi.cn/")
               .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
               .addConverterFactory(GsonConverterFactory.create())
               .build();


       ReSrevice reSrevice = retrofit.create(ReSrevice.class);
       reSrevice.uploadImage(map,parts).observeOn(AndroidSchedulers.mainThread())
               .subscribeOn(Schedulers.io())
               .subscribe(new Observer() {
                   @Override
                   public void onSubscribe(Disposable d) {


                   }


                   @Override
                   public void onNext(ResponseBody value) {
                       try {
                           Log.e("result", value.string());
                       } catch (IOException e) {
                           e.printStackTrace();
                       }
                   }


                   @Override
                   public void onError(Throwable e) {
                       Log.e("onError", e.toString());
                   }


                   @Override
                   public void onComplete() {


                   }
               });
}
 
  
    }
}
 
  
 
  
 
  
//utils
 
  
@POST("file/upload")
@Multipart
Observable upload(@Part("uid") RequestBody uid, @Part MultipartBody.Part file);

  //多图

 @POST("quarter/publishJoke")

    @Multipart
    Observable uploadImage(@QueryMap Map map, @Part List parts);
 
  
 
  
public Sres getnetjson(String uri){
           Retrofit retrofit = new Retrofit.Builder().baseUrl(uri)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
    Sres testservive = retrofit.create(Sres.class);
    return testservive;
}

 
 

你可能感兴趣的:(相机上传头像)