项目中都会有修改头像,上传照片到服务器的功能,简单来一个,可以直接用。xutils
public class UserMsgActivity extends BaseActivity { private CircleImageView pic;//头像 // 声明PopupWindow private PopupWindow popupWindow; // 声明PopupWindow对应的视图 private View popupView; // 声明平移动画 private TranslateAnimation animation; private String path = "/sdcard/myHeadPic/";// sd路径 private Bitmap head;//头像Bitmap private String mFilePath; private boolean picFlag = false; private String s; private String imageUrl; @Override public int getLayoutId() { return R.layout.activity_user_msg; } @Override public void initViews() { Intent intent = getIntent(); imageUrl = intent.getStringExtra("imageUrl"); // 文件名 mFilePath = path + "userhead.jpg"; pic = findView(R.id.pic); Logger.e("imsgeUrl--" + imageUrl); //设置头像,昵称,邮箱 if (imageUrl != null && !imageUrl.equals("")) { Glide.with(this).load(imageUrl).into(pic); } else { //没头像展示默认 pic.setImageResource(R.drawable.nologin_pic); } } @Override public void initListener() { setOnClick(pic); } @Override public void initData() { } @Override public void progressClick(View v) { switch (v.getId()) { case R.id.pic://修改图片 changeIcon(); break; } } /** * 弹出popupWindow */ private void changeIcon() { lightoff(); if (popupWindow == null) { popupView = View.inflate(this, R.layout.popup_uploading, null); // 参数2,3:指明popupwindow的宽度和高度 popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT); popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { popupWindow = null; lighton(); } }); // 设置背景图片,必须设置,不然动画没作用 popupWindow.setBackgroundDrawable(new BitmapDrawable()); popupWindow.setFocusable(true); // 设置点击popupwindow外屏幕其它地方消失 popupWindow.setOutsideTouchable(true); // 平移动画相对于手机屏幕的底部开始,X轴不变,Y轴从1变0 animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 1, Animation.RELATIVE_TO_PARENT, 0); animation.setInterpolator(new AccelerateInterpolator()); animation.setDuration(200); //退出 popupView.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupWindow.dismiss(); lighton(); } }); //从相册选择 popupView.findViewById(R.id.photo_album).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent1 = new Intent(Intent.ACTION_PICK, null); intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(intent1, 1); popupWindow.dismiss(); lighton(); } }); //拍照 popupView.findViewById(R.id.take_pic).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //// 指定存储路径,这样就可以保存原图了 intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "userhead.jpg"))); startActivityForResult(intent2, 2);// 采用ForResult打开 popupWindow.dismiss(); lighton(); } }); } // 在点击之后设置popupwindow的销毁 if (popupWindow.isShowing()) { popupWindow.dismiss(); lighton(); } // 设置popupWindow的显示位置,此处是在手机屏幕底部且水平居中的位置 popupWindow.showAtLocation(pic, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); popupView.startAnimation(animation); } /** * 设置手机屏幕亮度变暗 */ private void lightoff() { WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 0.3f; getWindow().setAttributes(lp); } /** * 设置手机屏幕亮度显示正常 */ private void lighton() { WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 1f; getWindow().setAttributes(lp); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case 1://相册 if (resultCode == RESULT_OK) { cropPhoto(data.getData());// 裁剪图片 Log.e("--main--", "--11---22--" + data.getData()); } break; case 2://拍照 if (resultCode == RESULT_OK) { //;这个是设置文件名 File temp = new File(Environment.getExternalStorageDirectory() + "/userhead.jpg"); cropPhoto(Uri.fromFile(temp));// 裁剪图片 Log.e("--main--", "--33--55--" + Uri.fromFile(temp)); } break; case 3://裁剪 if (data != null) { Bundle extras = data.getExtras(); head = extras.getParcelable("data"); if (head != null) { setPicToView(head);// 保存在SD卡中 /** * 上传服务器代码 */ s = PictureUtils.compressImage(mFilePath); picFlag = true; Log.e("--main--", "-3333--6666--" + PictureUtils.compressImage(mFilePath)); pic.setImageBitmap(head);// 用ImageView显示出来 if (s != null) { uploadPicture(s); } } } break; default: break; } //修改昵称返回 if (requestCode == 2333 && resultCode == 3332) { String name = data.getStringExtra("name"); user_name.setText(name); } //修改邮箱返回 if (requestCode == 2666 && resultCode == 6662) { String email = data.getStringExtra("email"); user_email.setText(email); } } private void uploadPicture(String s) { if (!picFlag) { ToastUtil.showToast("请上传照片"); return; } Logger.e("修改头像接口--" + UrlUtils.editUserMsgUrl); RequestParams params = new RequestParams(); params.addHeader("token", SharePrefManager.getToken()); params.addHeader("userId", SharePrefManager.getUserId()); HttpUtils xhttp = new com.lidroid.xutils.HttpUtils(); File file = new File(s); params.addBodyParameter("userId", SharePrefManager.getUserId()); params.addBodyParameter("type", "1"); params.addBodyParameter("icon", file); xhttp.send(HttpRequest.HttpMethod.POST, UrlUtils.editUserMsgUrl, params, new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { Logger.e("post-修改头像数据--" + responseInfo.result); Gson gson = new Gson(); Modification modification = gson.fromJson(responseInfo.result, Modification.class); if (modification != null && modification.getCode().equals("0000")) { ToastUtil.showToast("修改头像成功"); } else { ToastUtil.showToast("修改头像失败,请重试"); } } @Override public void onFailure(HttpException error, String msg) { ToastUtil.showToast("网络错误,请检查网络"); Logger.e("post-修改头像--error"); } }); } /** * 将图片保存到SD卡上面 * * @param */ private void setPicToView(Bitmap mBitmap) { String sdStatus = Environment.getExternalStorageState(); if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用 ToastUtil.showToast("SD卡不可用"); return; } FileOutputStream b = null; File file = new File(path); file.mkdirs();// 创建文件夹 String fileName = path + "userhead.jpg";// 图片名字 Log.e("--main--", fileName + "--==----111"); try { b = new FileOutputStream(fileName); //第2个参数表示压缩率,100表示不压缩 mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件 } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { if (b != null) { b.flush(); b.close(); b = null; } } catch (IOException e) { e.printStackTrace(); } } } // 裁剪图片 private void cropPhoto(Uri uri) { Intent intent = new Intent("com.android.camera.action.CROP"); 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, 3); } }