Retrofit头像上传

在这里插入图片描述

1.主页面布局

<?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:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/UpImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        />


    <LinearLayout
        android:id="@+id/Lin"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:visibility="gone"
        android:padding="15dp"
        >

        <Button
            android:id="@+id/xiangji"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="相机"
            android:textSize="20sp"
            />
        <Button
            android:id="@+id/xiangce"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="相册"
            android:textSize="20dp"
            />
        <Button
            android:id="@+id/callback"
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="取消"
            android:textSize="20sp"
            />

    </LinearLayout>

</RelativeLayout>

2.主页面代码

package com.bawie.image1;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView UpImage;
    private Button xiangji;
    private Button xiangce;
    private Button callback;
    private LinearLayout Lin;

    private final int ONE = 1;
    private final int TWO = 2;
    private final int THREE = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();


    }

    private void initView() {
        UpImage = (ImageView) findViewById(R.id.UpImage);
        xiangji = (Button) findViewById(R.id.xiangji);
        xiangce = (Button) findViewById(R.id.xiangce);
        callback = (Button) findViewById(R.id.callback);
        Lin = (LinearLayout) findViewById(R.id.Lin);

        xiangji.setOnClickListener(this);
        xiangce.setOnClickListener(this);
        callback.setOnClickListener(this);

        //更换头像
        UpImage.setOnClickListener(new View.OnClickListener() {
            private Button callback;

            @Override
            public void onClick(View v) {
                Lin.setVisibility(View.VISIBLE);
            }
        });
    }
    private void xiangji() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent,ONE);
    }

    private void xiangce() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent,TWO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
                case ONE:
                    //相机返回数据
                    if(data != null){
                        //获取相机图片获取
                        Bitmap bitmap = data.getParcelableExtra("data");
                        Uri temp = getBitmap(bitmap, "temp");
                        startImageZoom(temp);
                    }
                    break;
                case TWO:
                    if(data != null){
                        //用户从图库选择图片后会返回所选图片的Uri
                        Uri uri;
                        //获取到用户所选图片的Uri
                        uri = data.getData();
                        //返回的Uri为content类型的Uri,不能进行复制等操作,需要转换为文件Uri
                        uri = convertUri(uri);
                        startImageZoom(uri);
                    }
                    break;
                case THREE:
                    Bundle data1 = data.getExtras();
                    if (data1 != null){
                        //获取剪裁后的图片
                        Bitmap data2 = data1.getParcelable("data");
                        File file = getFile(data2);
                        //设置本地头像
                        UpImage.setImageBitmap(data2);
                        //设置文件设置图片的格式
                        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
                        //设置一个file文件
                        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
                        RetrofitUtils.getInstance().getImage(72, body)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Observer<ImageBean>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(ImageBean imageBean) {
                                    Toast.makeText(MainActivity.this,imageBean.getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            });
                    }
                    break;
            }
        }


    /**
     * 将Bitmap文件写入SD卡中,并且返回Uri
     */
    private Uri getBitmap(Bitmap bitmap, String temp) {
        //新建文件夹用于存放裁剪后的图片
        File file = new File(Environment.getExternalStorageDirectory() + "/" + temp);
        if(!file.exists()){
            file.mkdir();
        }
        //新建文件存储裁剪后的图片
        File img = new File(file.getAbsolutePath() + "/attr.png");
        try {
            //打开文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream(img);
            //将bitmap压缩后写入输出流(参数依次为图片格式、图片质量和输出流)
            bitmap.compress(Bitmap.CompressFormat.PNG,85,fileOutputStream);
            //刷新输出流
            fileOutputStream.flush();
            //关闭输出流
            fileOutputStream.close();
            //返回File类型的Uri
            return Uri.fromFile(img);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将content类型的Uri转化为文件类型的Uri
     * @param uri
     * @return
     */
    private Uri convertUri(Uri uri){
        InputStream is;
        try {
            //Uri ----> InputStream
            is = getContentResolver().openInputStream(uri);
            //InputStream ----> Bitmap
            Bitmap bm = BitmapFactory.decodeStream(is);
            //关闭流
            is.close();
            return getBitmap(bm, "temp");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }



    /**
     * 裁剪图片
     */
    public void startImageZoom(Uri uri){
        //构建隐式Intent来启动程序
        Intent intent = new Intent("com.android.camera.action.CROP");
        //设置为图片类型
        intent.setDataAndType(uri,"image/*");
        //显示View为可裁剪
        intent.putExtra("crop",true);
        //裁剪宽高比例
        intent.putExtra("aspectX",1);
        intent.putExtra("aspectY",1);
        //输出图片的宽高
        intent.putExtra("outputX",250);
        intent.putExtra("outputY",250);
        //裁剪之后的数据时通过Intent返回
        intent.putExtra("return-data",true);
        startActivityForResult(intent,THREE);
    }
    //Bitmap转换成file
    public File getFile(Bitmap bmp) {
        String defaultPath = getApplicationContext().getFilesDir()
                .getAbsolutePath() + "/defaultGoodInfo";
        File file = new File(defaultPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String defaultImgPath = defaultPath + "/messageImg.jpg";
        file = new File(defaultImgPath);
        try {
            file.createNewFile();
            FileOutputStream fOut = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 20, fOut);
            fOut.flush();
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.callback:
                Lin.setVisibility(View.GONE);
                break;
            case R.id.xiangji:
                xiangji();
                Lin.setVisibility(View.GONE);
                break;
            case R.id.xiangce:
                xiangce();
                Lin.setVisibility(View.GONE);
                break;
        }
    }


}

3.工具
(1)RetrofitUtils:

package com.bawie.image1;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * date:2018/12/20
 * author:KK(别来无恙)
 * function:
 */
public class RetrofitUtils {
    /*private static RetrofitUtils mRetrofitUtils;
    private final Retrofit mRetrofit;

    private RetrofitUtils(){
        mRetrofit = new Retrofit.Builder()
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Constance.URL_TOPHAEDS)
                .build();
    }
    public static RetrofitUtils getInstance(){
        if (mRetrofitUtils == null){
            synchronized (RetrofitUtils.class){
                if (mRetrofitUtils == null){
                    return mRetrofitUtils = new RetrofitUtils();
                }
            }
        }
        return mRetrofitUtils;
    }

    public <T> T create(Class<T> clazz){
        return mRetrofit.create(clazz);
    }*/

    public static RetrofitService getInstance(){
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(3, TimeUnit.SECONDS)
                .readTimeout(3, TimeUnit.SECONDS)
                .writeTimeout(3, TimeUnit.SECONDS)
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(Constance.URL_TOPHAEDS)
                .client(okHttpClient)
                .build();
        RetrofitService retrofitService = retrofit.create(RetrofitService.class);
        return retrofitService;
    }

}

(2)RetrofitService:

public interface RetrofitService {

    @Multipart
    @POST("file/upload")
    Observable<ImageBean> getImage(@Query("uid") int uid, @Part MultipartBody.Part file);
}

(3)bean

public class ImageBean {

    /**
     * msg : 文件上传成功
     * code : 0
     */

    private String msg;
    private String code;

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

(4)constance:

public static final  String URL_TOPHAEDS="http://www.zhaoapi.cn/";

4.权限

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

	/*retrofit网络请求*/
    implementation 'com.squareup.retrofit2:retrofit:2.1.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
    /*eventbus传值*/
    implementation 'org.greenrobot:eventbus:3.0.0'
    /*RxAndroid所依赖的库*/
    implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
    implementation 'io.reactivex:rxandroid:1.2.1'
    implementation 'io.reactivex:rxjava:1.1.6'
    /*fresco图片处理*/
    implementation 'com.facebook.fresco:fresco:1.11.0'
发布了57 篇原创文章 · 获赞 12 · 访问量 8333
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览