效果图
首先添加依赖
compile 'com.facebook.fresco:fresco:0.8.1+' compile 'org.greenrobot:eventbus:3.1.1' compile 'io.reactivex.rxjava2:rxjava:2.1.7' compile 'io.reactivex.rxjava2:rxandroid:2.0.1' compile 'com.squareup.retrofit2:retrofit:2.3.0' compile 'com.squareup.retrofit2:converter-gson:2.3.0' compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' compile 'com.jakewharton:butterknife:8.8.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
权限
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
ApiService
public interface ApiService { // https://www.zhaoapi.cn/file/upload @Multipart @POST("upload") Flowable<MessageBean> getMusicList(@Query("uid") String uid, @Part MultipartBody.Part file); }
BasePresenter
public interface BasePresenter{ void getData(String uid, MultipartBody.Part file); }
ImageUtils
public class ImageUtils { /** * Save image to the SD card * * @param photoBitmap * @param photoName * @param path */ public static String savePhoto(Bitmap photoBitmap, String path, String photoName) { String localPath = null; if (android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED)) { File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } File photoFile = new File(path, photoName + ".png"); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(photoFile); if (photoBitmap != null) { if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)) { // 转换完成 localPath = photoFile.getPath(); fileOutputStream.flush(); } } } catch (FileNotFoundException e) { photoFile.delete(); localPath = null; e.printStackTrace(); } catch (IOException e) { photoFile.delete(); localPath = null; e.printStackTrace(); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); fileOutputStream = null; } } catch (IOException e) { e.printStackTrace(); } } } return localPath; } /** * 转换图片成圆形 * * @param bitmap 传入Bitmap对象 * @return */ public static Bitmap toRoundBitmap(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); float roundPx; float left,top,right,bottom,dst_left,dst_top,dst_right,dst_bottom; if (width <= height) { roundPx = width / 2; top = 0; bottom = width; left = 0; right = width; height = width; dst_left = 0; dst_top = 0; dst_right = width; dst_bottom = width; } else { roundPx = height / 2; float clip = (width - height) / 2; left = clip; right = width - clip; top = 0; bottom = height; width = height; dst_left = 0; dst_top = 0; dst_right = height; dst_bottom = height; } Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect src = new Rect((int)left, (int)top, (int)right, (int)bottom); final Rect dst = new Rect((int)dst_left, (int)dst_top, (int)dst_right, (int)dst_bottom); final RectF rectF = new RectF(dst); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, src, dst, paint); return output; } }
MainActivity
public class MainActivity extends AppCompatActivity implements NewsView { @BindView(R.id.my_image_view) ImageView imageView; @BindView(R.id.btn_xiangji) Button mBtnXiangji; @BindView(R.id.btn_xiangce) Button mBtnXiangce; @BindView(R.id.btn_cancel) Button mBtnCancel; private File tempFile; private static final String PHOTO_FILE_NAME = "temp_photo.jpg"; private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照 private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择 private static final int PHOTO_REQUEST_CUT = 3;// 结果 private NewsPresenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); presenter = new NewsPresenter(); presenter.attachView(this); } @OnClick({R.id.my_image_view, R.id.btn_xiangji, R.id.btn_xiangce, R.id.btn_cancel}) public void onClick(View v) { switch (v.getId()) { default: break; case R.id.my_image_view: break; case R.id.btn_xiangji: // 激活相机 Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); // 判断存储卡是否可以用,可用进行存储 if (hasSdcard()) { tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME); // 从文件中创建uri Uri uri = Uri.fromFile(tempFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); } // 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CAREMA startActivityForResult(intent, PHOTO_REQUEST_CAREMA); break; case R.id.btn_xiangce: // 激活系统图库,选择一张图片 Intent intent1 = new Intent(Intent.ACTION_PICK); intent1.setType("image/*"); // 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_GALLERY startActivityForResult(intent1, PHOTO_REQUEST_GALLERY); break; case R.id.btn_cancel: break; } } /* * 判断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); } @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(MainActivity.this, "未找到存储卡,无法存储照片!", Toast.LENGTH_SHORT).show(); } } else if (requestCode == PHOTO_REQUEST_CUT) { // 从剪切图片返回的数据 if (data != null) { Bitmap bitmap = data.getParcelableExtra("data"); /** * 获得图片 */ imageView.setImageBitmap(bitmap); setImgByStr( bitmap); } try { // 将临时文件删除 tempFile.delete(); } catch (Exception e) { e.printStackTrace(); } } super.onActivityResult(requestCode, resultCode, data); } /** * 上传头像 */ public void setImgByStr(Bitmap bitmap) { if(bitmap != null){ // 拿着imagePath上传了 // ... } String imagePath = ImageUtils.savePhoto(bitmap, Environment .getExternalStorageDirectory().getAbsolutePath(), String .valueOf(System.currentTimeMillis())); Log.d("zxz","imagePath:"+imagePath); if(imagePath!=null){ 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); MultipartBody.Part photo = MultipartBody.Part.createFormData("file", file.getName(), photoRequestBody); presenter.getData("71",photo); } } @Override protected void onResume() { super.onResume(); } @Override public void onSuccess(MessageBean messageBean) { String msg = messageBean.getMsg(); Log.e("zxz",msg); } }
MessageBean
public class MessageBean { /** * msg : 请求成功 * code : 0 * data : [{"list":[{"bargainPrice":99,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/4345173.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t6037/35/2944615848/95178/6cd6cff0/594a3a10Na4ec7f39.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6607/258/1025744923/75738/da120a2d/594a3a12Ne3e6bc56.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6370/292/1057025420/64655/f87644e3/594a3a12N5b900606.jpg!q70.jpg","num":2,"pid":45,"price":2999,"pscid":39,"selected":0,"sellerid":1,"subhead":"高清双摄,就是清晰!2000+1600万高清摄像头,6GB大内存+高通骁龙835处理器,性能怪兽!","title":"一加手机5 (A5000) 6GB+64GB 月岩灰 全网通 双卡双待 移动联通电信4G手机"}],"sellerName":"商家1","sellerid":"1"},{"list":[{"bargainPrice":1599,"createtime":"2017-10-14T21:48:08","detailUrl":"https://item.m.jd.com/product/1993026402.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t5863/302/8961270302/97126/41feade1/5981c81cNc1b1fbef.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t7003/250/1488538438/195825/53bf31ba/5981c57eN51e95176.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5665/100/8954482513/43454/418611a9/5981c57eNd5fc97ba.jpg!q70.jpg","num":12,"pid":47,"price":111,"pscid":39,"selected":0,"sellerid":3,"subhead":"碳黑色 32GB 全网通 官方标配 1件","title":"锤子 坚果Pro 特别版 巧克力色 酒红色 全网通 移动联通电信4G手机 双卡双待 碳黑色 32GB 全网通"}],"sellerName":"商家3","sellerid":"3"},{"list":[{"bargainPrice":1999,"createtime":"2017-10-10T16:09:02","detailUrl":"https://item.m.jd.com/product/5025971.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t7210/232/3738666823/232298/9004583e/59c3a9a7N8de42e15.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t8356/82/2107423621/109733/c019b8c6/59c3a9a6Ne9a4bdd7.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t10219/74/25356012/171379/7d55e296/59c3a9a8N82fa6e02.jpg!q70.jpg","num":1,"pid":49,"price":333,"pscid":39,"selected":0,"sellerid":5,"subhead":"vivo X20 带你开启全面屏时代!逆光也清晰,照亮你的美!","title":"vivo X20 全面屏手机 全网通 4GB+64GB 金色 移动联通电信4G手机 双卡双待"}],"sellerName":"商家5","sellerid":"5"},{"list":[{"bargainPrice":11800,"createtime":"2017-10-03T23:53:28","detailUrl":"https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1","images":"https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg","num":1,"pid":62,"price":15999,"pscid":40,"selected":0,"sellerid":6,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"}],"sellerName":"商家6","sellerid":"6"},{"list":[{"bargainPrice":11800,"createtime":"2017-10-14T21:48:08","detailUrl":"https://mitem.jd.hk/ware/view.action?wareId=1988853309&cachekey=1acb07a701ece8d2434a6ae7fa6870a1","images":"https://m.360buyimg.com/n0/jfs/t6130/97/1370670410/180682/1109582a/593276b1Nd81fe723.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5698/110/2617517836/202970/c9388feb/593276b7Nbd94ef1f.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5815/178/2614671118/51656/7f52d137/593276c7N107b725a.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t5878/60/2557817477/30873/4502b606/593276caN5a7d6357.jpg!q70.jpg","num":1,"pid":68,"price":15000,"pscid":40,"selected":0,"sellerid":12,"subhead":"购买电脑办公部分商品满1元返火车票5元优惠券(返完即止)","title":"全球购 新款Apple MacBook Pro 苹果笔记本电脑 银色VP2新13英寸Bar i5/8G/256G"}],"sellerName":"商家12","sellerid":"12"}] */ private String msg; private String code; private List<DataBean> data; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public List<DataBean> getData() { return data; } public void setData(List<DataBean> data) { this.data = data; } public static class DataBean { /** * list : [{"bargainPrice":99,"createtime":"2017-10-14T21:38:26","detailUrl":"https://item.m.jd.com/product/4345173.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends","images":"https://m.360buyimg.com/n0/jfs/t6037/35/2944615848/95178/6cd6cff0/594a3a10Na4ec7f39.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6607/258/1025744923/75738/da120a2d/594a3a12Ne3e6bc56.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6370/292/1057025420/64655/f87644e3/594a3a12N5b900606.jpg!q70.jpg","num":2,"pid":45,"price":2999,"pscid":39,"selected":0,"sellerid":1,"subhead":"高清双摄,就是清晰!2000+1600万高清摄像头,6GB大内存+高通骁龙835处理器,性能怪兽!","title":"一加手机5 (A5000) 6GB+64GB 月岩灰 全网通 双卡双待 移动联通电信4G手机"}] * sellerName : 商家1 * sellerid : 1 */ private String sellerName; private String sellerid; private List<ListBean> list; private boolean checked; public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } public String getSellerName() { return sellerName; } public void setSellerName(String sellerName) { this.sellerName = sellerName; } public String getSellerid() { return sellerid; } public void setSellerid(String sellerid) { this.sellerid = sellerid; } public List<ListBean> getList() { return list; } public void setList(List<ListBean> list) { this.list = list; } public static class ListBean { /** * bargainPrice : 99.0 * createtime : 2017-10-14T21:38:26 * detailUrl : https://item.m.jd.com/product/4345173.html?utm#_source=androidapp&utm#_medium=appshare&utm#_campaign=t#_335139774&utm#_term=QQfriends * images : https://m.360buyimg.com/n0/jfs/t6037/35/2944615848/95178/6cd6cff0/594a3a10Na4ec7f39.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6607/258/1025744923/75738/da120a2d/594a3a12Ne3e6bc56.jpg!q70.jpg|https://m.360buyimg.com/n0/jfs/t6370/292/1057025420/64655/f87644e3/594a3a12N5b900606.jpg!q70.jpg * num : 2 * pid : 45 * price : 2999.0 * pscid : 39 * selected : 0 * sellerid : 1 * subhead : 高清双摄,就是清晰!2000+1600万高清摄像头,6GB大内存+高通骁龙835处理器,性能怪兽! * title : 一加手机5 (A5000) 6GB+64GB 月岩灰 全网通 双卡双待 移动联通电信4G手机 */ private double bargainPrice; private String createtime; private String detailUrl; private String images; private int num; private int pid; private double price; private int pscid; private int selected; private int sellerid; private String subhead; private String title; private boolean checked; public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } public double getBargainPrice() { return bargainPrice; } public void setBargainPrice(double bargainPrice) { this.bargainPrice = bargainPrice; } public String getCreatetime() { return createtime; } public void setCreatetime(String createtime) { this.createtime = createtime; } public String getDetailUrl() { return detailUrl; } public void setDetailUrl(String detailUrl) { this.detailUrl = detailUrl; } public String getImages() { return images; } public void setImages(String images) { this.images = images; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getPscid() { return pscid; } public void setPscid(int pscid) { this.pscid = pscid; } public int getSelected() { return selected; } public void setSelected(int selected) { this.selected = selected; } public int getSellerid() { return sellerid; } public void setSellerid(int sellerid) { this.sellerid = sellerid; } public String getSubhead() { return subhead; } public void setSubhead(String subhead) { this.subhead = subhead; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } } }
NewModel
public class NewModel { private NewsPresenter presenter; public NewModel(NewsPresenter presenter) { this.presenter = presenter; } public void getData(String uid , MultipartBody.Part file){ Flowable<MessageBean> flowable = RetrofitUtils.getInstance().getService().getMusicList(uid, file); presenter.getNews(flowable); } }
NewsPresenter
public class NewsPresenter implements BasePresenter{ private NewsView inv; private DisposableSubscriber<MessageBean> disposableSubscriber; public void attachView(NewsView inv){ this.inv = inv; } public void detachView(){ // 当Activity销毁的时候取消订阅时间,防止内存泄漏 if (disposableSubscriber != null) { if (disposableSubscriber.isDisposed()) { disposableSubscriber.dispose(); } } if (inv!=null){ inv = null; } } @Override public void getData(String uid, MultipartBody.Part file) { NewModel newModel = new NewModel(this); newModel.getData(uid,file); } public void getNews(Flowable<MessageBean> flowable) { disposableSubscriber = flowable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(new DisposableSubscriber<MessageBean>() { @Override public void onNext(MessageBean messageBean) { if(messageBean!=null){ inv.onSuccess(messageBean); } } @Override public void onError(Throwable t) { Log.e("zxz",t.getMessage()); } @Override public void onComplete() { } }); } }
NewsView
public interface NewsView { void onSuccess(MessageBean messageBean); }
RetrofitUtils
public class RetrofitUtils { private static volatile RetrofitUtils instance; private Retrofit retrofit; private ApiService apiService; private RetrofitUtils(){ OkHttpClient client = new OkHttpClient(); retrofit = new Retrofit.Builder() .client(client) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl("http://120.27.23.105/file/") .build(); apiService = retrofit.create(ApiService.class); } public static RetrofitUtils getInstance(){ if (instance==null){ synchronized (RetrofitUtils.class){ if (null==instance){ instance = new RetrofitUtils(); } } } return instance; } public ApiService getService(){ return apiService; } }
activity_main
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:fresco="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.hongliang1510d20180104.MainActivity"> <!--com.facebook.drawee.view.SimpleDraweeView fresco:placeholderImage="@mipmap/ic_launcher"--> <ImageView android:id="@+id/my_image_view" android:layout_width="130dp" android:layout_height="130dp" android:src="@mipmap/ic_launcher_round" android:layout_centerHorizontal="true" /> <LinearLayout android:layout_alignParentBottom="true" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="wrap_content"> <Button android:id="@+id/btn_xiangji" android:text="相机" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_xiangce" android:text="相册" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_cancel" android:text="取消" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </RelativeLayout>