1.添加支持包
implementation 'com.github.lovetuzitong:MultiImageSelector:1.2'
2.在AndroidManifest.xml添加权限

   <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <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.CAMERA"/>
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-feature android:name="android.hardware.screen.landscape"/>
    <uses-feature android:name="android.hardware.wifi" android:required="false"/>
    <uses-feature android:name="android.hardware.touchscreen"/>
 

3.代码

package request.http.com.httprequest.fragment.my;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.nereo.multi_image_selector.MultiImageSelector;
import request.http.com.httprequest.R;
import request.http.com.httprequest.activity.MainActivity;
import request.http.com.httprequest.bean.avatarBean;
import request.http.com.httprequest.common.Tools;
import request.http.com.httprequest.fragment.main.homeMyFragment;

import static android.app.Activity.RESULT_OK;
import static android.content.Context.MODE_PRIVATE;
import static android.os.Environment.getExternalStorageDirectory;

/**
 * Date: 2019/7/15
 * Time: 17:03
 * author:Guest
 */
public class avatarFragment extends Fragment implements View.OnClickListener {
    @BindView(R.id.iv_go_photo)
    ImageView iv_go_photo;
    @BindView(R.id.iv_qrcode_personal)
    ImageView iv_qrcode_personal;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_avatar , container , false);
        Unbinder unbinder = ButterKnife.bind(this,view);
        Message message = new Message();
        message.arg1 = 202;
        MainActivity.mainHandler.sendMessage(message);
        initView();
        initData();
        return view;
    }
    private  void initView(){  }
    private void initData(){
      pickImage();
    }

    private void pickImage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN 
          && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                    getString(R.string.mis_permission_rationale),
                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        }else {
            //多选
            //  int maxNum = 9;
          //     selector.count(maxNum);
            MultiImageSelector selector = MultiImageSelector.create(getActivity());
          //单选
            selector.single();
            selector.origin(mSelectPath);
            selector.start(getActivity(), REQUEST_IMAGE);
        }
    }
    private void requestPermission(final String permission, String rationale, final int requestCode){
        if(ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), permission)){
            new AlertDialog.Builder(getContext())
                    .setTitle(R.string.mis_permission_dialog_title)
                    .setMessage(rationale)
                    .setPositiveButton(R.string.mis_permission_dialog_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(getActivity(), new String[]{permission}, requestCode);
                        }
                    })
                    .setNegativeButton(R.string.mis_permission_dialog_cancel, null)
                    .create().show();
        }else{
            ActivityCompat.requestPermissions(getActivity(), new String[]{permission}, requestCode);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode == REQUEST_STORAGE_READ_ACCESS_PERMISSION){
            if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                pickImage();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_IMAGE){
            if(resultCode == RESULT_OK){
                mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                for(int i=0; i<mSelectPath.size();i++){
                    flag = 3;
                    iv_go_photo.setImageBitmap(BitmapFactory.decodeFile(mSelectPath.get(i)));
                    iv_qrcode_personal.setImageBitmap(BitmapFactory.decodeFile(mSelectPath.get(i)));
                    saveMyBitmap(BitmapFactory.decodeFile(mSelectPath.get(i)));
                }
            }
        }
    }
    public void saveMyBitmap(Bitmap bitmap)  {
        String imageName="saveAvatar"+".jpg";
        String headPath=getExternalStorageDirectory()+ "/"+"head";
        File headDir=new File(headPath);
        if(!headDir.exists()){
            headDir.mkdirs();
        }
        System.out.println(headPath+"\n"+headDir);
        FileOutputStream headFos=null;
        File headFile=null;
        try{
            //重命名并保存
            headFile=new File(headPath,imageName);
            headFile.createNewFile();
            headFos=new FileOutputStream(headFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, headFos);
            headFos.flush();

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(headFos!=null){
                try {
                    headFos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}









Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐