Android更换头像上传

来源:互联网 发布:最后的堡垒 知乎 编辑:程序博客网 时间:2024/04/27 19:45
AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);builder.setTitle("添加图片");String[] items = { "选择本地照片", "拍照" };builder.setNegativeButton("取消", null);builder.setItems(items, new DialogInterface.OnClickListener() {    @Override    public void onClick(DialogInterface dialog, int which) {        switch (which) {            case CHOOSE_PICTURE: // 选择本地照片                Intent openAlbumIntent = new Intent(                        Intent.ACTION_GET_CONTENT);                openAlbumIntent.setType("image/*");                //startActivityForResult方法,待会儿重写onActivityResult()方法,拿到图片做裁剪操作                startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);                break;            case TAKE_PICTURE: // 拍照                Intent openCameraIntent = new Intent(                        MediaStore.ACTION_IMAGE_CAPTURE);                tempUri = Uri.fromFile(new File(Environment                        .getExternalStorageDirectory(), "temp_image.jpg"));                // 将拍照所得的相片保存到SD卡根目录                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);                startActivityForResult(openCameraIntent, TAKE_PICTURE);                break;        }    }});builder.show();
/**     * 上传服务器     * @param mobile     * @param file     */    public void touimg(String mobile, File file){        Map<String,Object> params=new HashMap<>();        params.put("uid",mobile);        OkHttpClient okHttpClient=new OkHttpClient();        MultipartBody.Builder builder=new MultipartBody.Builder().setType(MultipartBody.FORM);        RequestBody requestBody=RequestBody.create(MediaType.parse("image/*"),file);        builder.addFormDataPart("file",file.getName(),requestBody);        if(params!=null){            for (Map.Entry entry : params.entrySet()) {                builder.addFormDataPart(valueOf(entry.getKey()), valueOf(entry.getValue()));            }            Request request=new Request.Builder().url(Api.ICONIMG_API).post(builder.build()).build();            Call call = okHttpClient.newCall(request);            call.enqueue(new Callback() {                @Override                public void onFailure(Call call, IOException e) {                    System.out.println("=======失败了===");                }                @Override                public void onResponse(Call call, Response response) throws IOException {                    System.out.println("=======成功了===");                }            });        }    }    @Override    public void onActivityResult(int requestCode, int resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        if (resultCode == MainActivity.RESULT_OK) {            switch (requestCode) {                case TAKE_PICTURE:                    cutImage(tempUri); // 对图片进行裁剪处理 拍照                    break;                case CHOOSE_PICTURE:                    cutImage(data.getData()); // 对图片进行裁剪处理                    break;                case CROP_SMALL_PICTURE:                    if (data != null) {                        try {                            setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上                        } catch (IOException e) {                            e.printStackTrace();                        }                    }                    break;            }        }    }    /**     * 裁剪图片方法实现     */    protected void cutImage(Uri uri) {        if (uri == null) {            Log.i("alanjet", "The uri is not exist.");        }        tempUri = uri;        Intent intent = new Intent("com.android.camera.action.CROP");        //com.android.camera.action.CROP这个action是用来裁剪图片用的        intent.setDataAndType(uri, "image/*");        // 设置裁剪        intent.putExtra("crop", "true");        // aspectX aspectY 是宽高的比例        intent.putExtra("aspectX", 1);        intent.putExtra("aspectY", 1);        // outputX outputY 是裁剪图片宽高        intent.putExtra("outputX", 150);        intent.putExtra("outputY", 150);        intent.putExtra("return-data", true);        startActivityForResult(intent, CROP_SMALL_PICTURE);    }    /**     * 保存裁剪之后的图片数据     */    protected void setImageToView(Intent data) throws IOException {        Bundle extras = data.getExtras();        if (extras != null) {            mBitmap = extras.getParcelable("data");            //这里图片是方形的,可以用一个工具类处理成圆形(很多头像都是圆形,这种工具类网上很多不再详述)            System.out.println("============="+mBitmap.toString());            saveFile(mBitmap,"icon_bai.jpg");//存到本地            System.out.println("dianjial");            iv_icon.setImageBitmap(mBitmap);//显示图片        }    }    /**     * bitmap 转换成file文件 .jpeg     * @param bm     * @param fileName     * @throws IOException     */    public void saveFile(Bitmap bm, String fileName) throws IOException {        String path = getSDPath() +"/revoeyee/";        File dirFile = new File(path);        if(!dirFile.exists()){            dirFile.mkdir();        }        File myCaptureFile = new File(path + fileName);        //bitmip 保存到本地缓存        //BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));        FileOutputStream bos=new FileOutputStream(myCaptureFile);        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);        touimg(uid,myCaptureFile);        /**         * 上传服务器         *///        HashMap<String,Object> map=new HashMap<>();//        map.put("mobile",name);//        post_file(Api.ICONIMG_API,map,myCaptureFile);        bos.flush();        bos.close();    }    /**     * 获取路径     * @return     */    public static String getSDPath(){        File sdDir = null;        boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在        if (sdCardExist)        {            sdDir = Environment.getExternalStorageDirectory();//获取跟目录        }        return sdDir.toString();    }    public void btn_user_tiaozhuan(View v){        startActivity(new Intent(this,SousuoActivity.class));    }