废话不多说,直接上代码了!!
activity
private SimpleDraweeView mine_zi_liao_userPhoto;
private TextView mine_zi_liao_mobile;
private TextView mine_zi_liao_username;
private PopupWindow mPopupWindowDialog;
private Button btn_take_photo;
private Button btn_pick_photo;
private Button btn_cancel;
private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
private static final int PHOTO_REQUEST_CUT = 3;// 结果
//点击弹出 popwindow 弹框
public void mine_zi_liao_userPhotos(View view) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi = inflater.inflate(R.layout.userphotopopwindow, null);
btn_take_photo = (Button) vi.findViewById(R.id.btn_take_photo);
btn_pick_photo = (Button) vi.findViewById(R.id.btn_pick_photo);
btn_cancel = (Button) vi.findViewById(R.id.btn_cancel);
btn_take_photo.setOnClickListener(this);
btn_pick_photo.setOnClickListener(this);
btn_cancel.setOnClickListener(this);
/*pop 设置*/
mPopupWindowDialog = new PopupWindow(vi, ActionBar.LayoutParams.FILL_PARENT, ActionBar.LayoutParams.WRAP_CONTENT);
mPopupWindowDialog.setFocusable(true);
mPopupWindowDialog.update();
mPopupWindowDialog.setBackgroundDrawable(new BitmapDrawable());
mPopupWindowDialog.setOutsideTouchable(true);
/*显示 pop 弹框*/
mPopupWindowDialog.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
}
}
/*选择弹框选项*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_take_photo:// 拍照
// 激活相机
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// 判断存储卡是否可以用,可用进行存储
if (hasSdcard()) {
tempFile = new File(Environment.getExternalStorageDirectory(), "temp_photo.jpg");
// 从文件中创建uri
Uri uri = Uri.fromFile(tempFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}
// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CAREMA
startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
if (mPopupWindowDialog != null && mPopupWindowDialog.isShowing()) {
mPopupWindowDialog.dismiss();
}
break;
case R.id.btn_pick_photo:// 相册
// 激活系统图库,选择一张图片
Intent intent1 = new Intent(Intent.ACTION_PICK);
intent1.setType("image/*");
// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_GALLERY
startActivityForResult(intent1, PHOTO_REQUEST_GALLERY);
if (mPopupWindowDialog != null && mPopupWindowDialog.isShowing()) {
mPopupWindowDialog.dismiss();
}
break;
case R.id.btn_cancel: // 取消
if (mPopupWindowDialog != null && mPopupWindowDialog.isShowing()) {
mPopupWindowDialog.dismiss();
}
break;
}
}
/**
* 返回结果
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PHOTO_REQUEST_GALLERY) {
// 从相册返回的数据
if (data != null) {
// 得到图片的全路径
Uri uri = data.getData();
crop(uri);
}
} else if (requestCode == PHOTO_REQUEST_CAREMA) {
// // 从相机返回的数据
if (hasSdcard()) {
crop(Uri.fromFile(tempFile));
} else {
Toast.makeText(MineZiLiaoActivity.this, "未找到存储卡,无法存储照片!", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == PHOTO_REQUEST_CUT) {
// 从剪切图片返回的数据
if (data != null) {
Bitmap bitmap = data.getParcelableExtra("data");
/**
* 获得图片
*/
mine_zi_liao_userPhoto.setImageBitmap(bitmap);
//保存到SharedPreferences
saveBitmapToSharedPreferences(bitmap);
}
try {
// 将临时文件删除
tempFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
/*
* 判断sdcard是否被挂载
*/
private boolean hasSdcard() {
//判断SD卡手否是安装好的 media_mounted
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}
/*
* 剪切图片
*/
private void crop(Uri uri) {
// 裁剪图片意图
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
// 裁剪框的比例,1:1
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// 裁剪后输出图片的尺寸大小
intent.putExtra("outputX", 250);
intent.putExtra("outputY", 250);
intent.putExtra("outputFormat", "JPEG");// 图片格式
intent.putExtra("noFaceDetection", true);// 取消人脸识别
intent.putExtra("return-data", true);
// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CUT
startActivityForResult(intent, PHOTO_REQUEST_CUT);
}
//保存图片到SharedPreferences
private void saveBitmapToSharedPreferences(Bitmap bitmap) {
// Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
//第一步:将Bitmap压缩至字节数组输出流ByteArrayOutputStream
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
//第二步:利用Base64将字节数组输出流中的数据转换成字符串String
byte[] byteArray = byteArrayOutputStream.toByteArray();
String imageString = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));
//第三步:将String保持至SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences("huangxiaoer", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("image", imageString);
editor.commit();
//上传头像
setImgByStr(bitmap);
}
/**
* 上传头像
*/
public void setImgByStr(Bitmap bitmap) {
if (bitmap != null) {
// 拿着imagePath上传了
}
String imagePath = ImageUtil.savePhoto(bitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), String.valueOf(System.currentTimeMillis()));
File file = new File(imagePath);//将要保存图片的路径
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
RequestBody photoRequestBody = RequestBody.create(MediaType.parse("image/png"), file);
photouri = MultipartBody.Part.createFormData("file", file.getName(), photoRequestBody);
/*头像*/
presenter.getPuserphoto(uid, photouri);
}
//这个看自己的需求,需要时添加即可
/* //从SharedPreferences获取图片
private void getBitmapFromSharedPreferences() {
SharedPreferences sharedPreferences = getSharedPreferences("testSP", Context.MODE_PRIVATE);
//第一步:取出字符串形式的Bitmap
String imageString = sharedPreferences.getString("image", "");
//第二步:利用Base64将字符串转换为ByteArrayInputStream
byte[] byteArray = Base64.decode(imageString, Base64.DEFAULT);
if (byteArray.length == 0) {
mine_zi_liao_userPhoto.setImageResource(R.mipmap.ic_launcher);
} else {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
//第三步:利用ByteArrayInputStream生成Bitmap
Bitmap bitmap = BitmapFactory.decodeStream(byteArrayInputStream);
mine_zi_liao_userPhoto.setImageBitmap(bitmap);
}
}
*/
retrofit 请求数据
/*上传图片*/
public void getMUserphoto(int uid, MultipartBody.Part photouri) {
RetrofitApi retrofitInterface = RetrofitUtil.getInstance().getRetrofitInterface();
Observable user = retrofitInterface.getUserPhotoBean(uid, photouri);
user.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(UserPhotoBean userPhotoBean) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
APi 接口
/**
* 上传头像
* https://www.zhaoapi.cn/file/upload?uid=15005&file=?
*/
@POST("file/upload")
@Multipart
Observable getUserPhotoBean(@Query("uid") int uid, @Part MultipartBody.Part file);
retrofitutil工具类
public class RetrofitUtil {
private Retrofit retrofit;
private static RetrofitUtil retrofitUtil;
private RetrofitUtil() {
}
private RetrofitUtil(String baseUrl) {
//第三方的日志拦截器
HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//OKhttp3 设置拦截器打印日志
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.addInterceptor(logInterceptor)
.build();
retrofit = new Retrofit.Builder().baseUrl(baseUrl) //设置网络请求的Url地址
.addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())//支持RxJava2平台
.client(okHttpClient)//OKhttp3添加到Retrofit
.build();
}
//可指定baseUrl
public static RetrofitUtil getInstance(String baseUrl) {
if (retrofitUtil == null) {
synchronized (RetrofitUtil.class) {
if (null == retrofitUtil) {
retrofitUtil = new RetrofitUtil(baseUrl);
}
}
}
return retrofitUtil;
}
//默认的baseUrl
public static RetrofitUtil getInstance() {
if (null == retrofitUtil) {
return getInstance("网址一部分, 要和Api 里进行拼接 例如 https://www.zhaoapi.cn/");
}
return retrofitUtil;
}
//获得Retrofit
public Retrofit getRetrofit() {
return retrofit;
}
//直接获得RetrofitInterface
public RetrofitApi getRetrofitInterface() {
RetrofitApi apiService = retrofit.create(RetrofitApi.class);
return apiService;
}
}
xml 布局
popwindow布局