您的位置:首页 > 移动开发 > Android开发

android——本地相机上传头像

2017-12-21 08:49 519 查看
添加依赖:

compile 'com.facebook.fresco:fresco:0.12.0'
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'

添加权限:

<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"/>


http
ApiService

public interface ApiService {
//    https://www.zhaoapi.cn/file/upload @Multipart
@POST("upload")
Flowable<MessageBean> getMusicList(@Query("uid") String uid,  @Part MultipartBody.Part file);

}

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;
}

}

model

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);
}
}

presenter

BasePresenter

public interface BasePresenter{
void getData(String uid, MultipartBody.Part file);
}

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() {

}
});
}

}

view

NewsView

public interface NewsView {
void onSuccess(MessageBean messageBean);
}

utils

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)
SimpleDraweeView mMyImageView;
@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");
/**
* 获得图片
*/
mMyImageView.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);
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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.bwie.com.songdechuan1220.MainActivity">

<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/my_image_view"
android:layout_width="130dp"
android:layout_height="130dp"
fresco:placeholderImage="@mipmap/ic_launcher" />
<LinearLayoutandroid: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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息