写这篇文章希望能帮助到各位有兴趣的同伴,这个功能一开始是因为公司要实现头像更换功能,虽然我是后端程序员,但是我这颗好学的心啊,真的是按捺不住。
所以就自己捣鼓了一下,还好完美实现了。首先是图片的点击事件,实现从相册选择图片和使用相机拍照并对选择和拍照后的图片进行裁剪功能,一下是主要代码:
/** * 显示修改图片的对话框 */ protected void showChoosePicDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.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 intent = new Intent(Intent.ACTION_PICK);//返回被选中项的URI intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");//得到所有图片的URI startActivityForResult(intent, 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(); }
然后是调用系统裁剪图片的功能:
@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("tip", "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"); //这里图片是方形的,可以用一个工具类处理成圆形(很多头像都是圆形,这种工具类网上很多不再详述) mImage.setImageBitmap(mBitmap);//显示图片 } File file = saveFile(mBitmap); upload(file);//上传裁剪后的图片 } public File saveFile(Bitmap bitmap) { File myCaptureFile = new File(path + fileName); File dirFile = new File(path); if (!dirFile.exists()) { dirFile.mkdir(); } BufferedOutputStream bos; try { bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile)); bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos); bos.flush(); bos.close(); } catch (IOException e) { e.printStackTrace(); } return myCaptureFile; }
到此对选择图片和拍照图片的裁剪功能实现了。接下来是把图片上传到服务器了。话不多说,直接贴代码:
public void upload(File file) { //创建Retrofit对象 //创建 网络请求接口 的实例 String descriptionString = "This is a params"; RequestBody uid = RequestBody.create(MediaType.parse("text/plain"), "14715689"); RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile); Call<Translation> call = new RetrofitUtil(Constant.UMS3_CLIENT2.getBaseUrl()).create(PostRequest_Interface.class).upload(uid, body); call.enqueue(new Callback<Translation>() { @Override public void onResponse(Call<Translation> call, Response<Translation> response) { System.out.println("result=" + response.body().toString()); if (response.body() != null) { try { Toast.makeText(MainActivity.this, "头像上传成功!", Toast.LENGTH_SHORT).show(); System.out.println("result=" + response.body().getResult() + ",headUrl=" + response.body().getHeadUrl()); } catch (Exception e) { e.printStackTrace(); } } } @Override public void onFailure(Call<Translation> call, Throwable t) { Toast.makeText(MainActivity.this, "头像上传失败!", Toast.LENGTH_SHORT).show(); t.printStackTrace(); } }); }
上传图片功能是用retrofit2.0实现的,关于这个框架的学习有兴趣的同学可以跳转到这里学习https://www.jianshu.com/p/86e5cddcc753。好了还有很多工具类就不贴出来了,有兴趣的同学可以下载上传的源代码:https://download.csdn.net/download/look_at_once/10561900。只需要一个积分,而且项目里面有服务单代码,欢迎大家下载