用户登录
用户注册

分享至

android中实现从相册中一次性获取多张图片与拍照,并将选中的图片显示出来

  • 作者: 我是要成为海贼老王的男人
  • 来源: 51数据库
  • 2021-09-01

1.自定义相册,实现多选


public class SelectAlbumActivity extends BaseActivity {

? ? private ArrayList<String> imageUrls;
? ? private DisplayImageOptions options;
? ? private ImageAdapter imageAdapter;
? ? @Override
? ? public void onCreate(Bundle savedInstanceState) {
? ? ? ? super.onCreate(savedInstanceState);
? ? ? ? setContentView(R.layout.ac_image_grid);

? ? ? ? initData();
? ? ? ? initGallery();
? ? }

? ? private void initData() {
? ? ? ? this.imageUrls = new ArrayList<String>();

? ? ? ? final String[] columns = {MediaStore.Images.Media.DATA,
? ? ? ? ? ? ? ? MediaStore.Images.Media._ID};
? ? ? ? final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
? ? ? ? Cursor imagecursor = this
? ? ? ? ? ? ? ? .getApplicationContext()
? ? ? ? ? ? ? ? .getContentResolver()
? ? ? ? ? ? ? ? .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
? ? ? ? ? ? ? ? ? ? ? ? null, null, orderBy + " DESC");
? ? ? ? for (int i = 0; i < imagecursor.getCount(); i++) {
? ? ? ? ? ? imagecursor.moveToPosition(i);
? ? ? ? ? ? int dataColumnIndex = imagecursor
? ? ? ? ? ? ? ? ? ? .getColumnIndex(MediaStore.Images.Media.DATA);
? ? ? ? ? ? imageUrls.add(imagecursor.getString(dataColumnIndex));
? ? ? ? ? ? Log.i("imageUrl", imageUrls.get(i));

? ? ? ? }
? ? }

? ? private void initGallery() {
? ? ? ? options = new DisplayImageOptions.Builder()
? ? ? ? ? ? ? ? .showStubImage(R.mipmap.add_icon)
? ? ? ? ? ? ? ? .showImageForEmptyUri(R.mipmap.ic_launcher)
? ? ? ? ? ? ? ? .cacheInMemory().cacheOnDisc().build();

? ? ? ? imageAdapter = new ImageAdapter(this, imageUrls);
? ? ? ? GridView gridView = (GridView) findViewById(R.id.gridview);
? ? ? ? gridView.setAdapter(imageAdapter);
? ? ? ? // gridView.setOnItemClickListener(new OnItemClickListener() {
? ? ? ? // @Override
? ? ? ? // public void onItemClick(AdapterView<?> parent, View view,
? ? ? ? // int position, long id) {
? ? ? ? // startImageGalleryActivity(position);
? ? ? ? // }
? ? ? ? // });
? ? }

? ? @Override
? ? protected void onStop() {
? ? ? ? imageLoader.stop();
? ? ? ? super.onStop();
? ? }

? ? public void btnChoosePhotosClick(View v) {
? ? ? ? Intent intent=getIntent();
? ? ? ? ArrayList<String> selectedItems = imageAdapter.getCheckedItems();

? ? ? ? for (int i=0;i<selectedItems.size();i++){
? ? ? ? ? ? Log.i("TAg------->Select",selectedItems.get(i));
? ? ? ? ? ? Toast.makeText(SelectAlbumActivity.this,selectedItems.get(i)+"",Toast.LENGTH_LONG).show();
? ? ? ? }
? ? ? ? Toast.makeText(SelectAlbumActivity.this,
? ? ? ? ? ? ? ? "Total photos selected: " + selectedItems.size(),
? ? ? ? ? ? ? ? Toast.LENGTH_SHORT).show();


? ? ? ? intent.putExtra("selectPic",selectedItems);
? ? ? ? setResult(RESULT_OK,intent);
? ? ? ? finish();
? ? }
? ?

}

2.WriteDiaryActivity.java将选中的图片显示出来

public class WriteDiaryActivity extends BaseActivity {

? ? EditText etWrite;
? ? GridView gv;
? ? private List<String> list = new ArrayList<String>();//存储选中图片的url

? ? private final int MAX_PHOTO = 10;//最多20张图
? ? private static final int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 1;
? ? private static final int MY_PERMISSIONS_READ_EXTERNAL_STORAGE = 2;
? ? private WriteDairyAdapter itemAdapter;


? ? private String imgPath;
? ? private int RESULT_LOAD_IMG=1;
? ? // 拍照的requestCode
? ? private static final int CAMERA_REQUEST_CODE = 0x00000010;
? ? // 申请相机权限的requestCode
? ? private static final int PERMISSION_CAMERA_REQUEST_CODE = 0x00000012;
? ? /**
? ? ?* 用于保存拍照图片的uri
? ? ?*/
? ? private Uri mCameraUri;

? ? /**
? ? ?* 用于保存图片的文件路径,Android 10以下使用图片路径访问图片
? ? ?*/
? ? private String mCameraImagePath;
? ? private int count=0;

? ? /**
? ? ?* ?是否是Android 10以上手机
? ? ?*/
? ? private boolean isAndroidQ = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
? ? @Override
? ? protected void onCreate(@Nullable Bundle savedInstanceState) {
? ? ? ? super.onCreate(savedInstanceState);
? ? ? ? setContentView(R.layout.activity_write_diary);
? ? ? ? initView();
? ? }

? ? private void initView() {

? ? ? ? etWrite=findViewById(R.id.etWrite);
? ? ? ? gv=findViewById(R.id.gvSelectPic);
? ? ? ? gv.setHorizontalSpacing(5);
? ? ? ? gv.setVerticalSpacing(5);


? ? ? ? list.add("default");

? ? ? ? itemAdapter = new WriteDairyAdapter(list,WriteDiaryActivity.this);

? ? ? ? gv.setAdapter(itemAdapter);
? ? ? ? gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ?initDialogGrade();
? ? ? ? ? ??
? ? ? ? ? ? }
? ? ? ? });

? ? }
// ? ?public void WriteClick(View view){
// ? ? ? ?switch (view.getId()){
// ? ? ? ? ? ?case R.id.ivBack:
// ? ? ? ? ? ? ? ?onBackPressed();
// ? ? ? ? ? ? ? ?break;
// ? ? ? ? ? ?case R.id.ivPhotoAlbum:
// ? ? ? ? ? ? ? ?initDialogGrade();
// ? ? ? ? ? ? ? ?getSystemService(Context.INPUT_METHOD_SERVICE);
// ? ? ? ? ? ? ? ?break;
// ? ? ? ? ? ?case R.id.btnCreate:
// ? ? ? ? ? ? ? ?break;
// ? ? ? ?}
// ? ?}
? ? private void initDialogGrade() {
? ? ? ? LayoutInflater inflater=LayoutInflater.from(WriteDiaryActivity.this);
? ? ? ? View view=inflater.inflate(R.layout.selelct_photo_dialog,null);
? ? ?
? ? ? ? TextView tv2=view.findViewById(R.id.tv2);
? ? ? ? TextView tv3=view.findViewById(R.id.tv3);

// ? ? ? ? ? ? ? ?点击默认图片


// ? ? ? ? ? ? ? ?view.setPadding(10,10,10,10);
? ? ? ? final Dialog dialog=new Dialog(WriteDiaryActivity.this);
? ? ? ? dialog.setContentView(view);
// ? ? ? ? ? ? ? ?dialog.create();
// ? ? ? ? ? ? ? ?任何区域关闭dialog
? ? ? ? dialog.setCanceledOnTouchOutside(true);

// ? ? ? ? ? ? ? ?dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_white_bg);
? ? ? ? dialog.show();
? ? ? ? Window window=dialog.getWindow();

? ? ? ? window.setGravity(Gravity.BOTTOM);
? ? ? ? window.getDecorView().setPadding(10,10,10,10);
? ? ? ? WindowManager manager=getWindowManager();
// ? ? ? ? ? ? ? ?获取屏幕的宽高
? ? ? ? Display display= manager.getDefaultDisplay();
? ? ? ? WindowManager.LayoutParams p=dialog.getWindow().getAttributes();
? ? ? ? p.width= display.getWidth();
? ? ? ? dialog.getWindow().setAttributes(p);
// ? ? ? ? ? ? ? ?打开拍照
? ? ? ? tv2.setOnClickListener(new View.OnClickListener() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void onClick(View v) {
? ? ? ? ? ? ? ? takePhoto();
? ? ? ? ? ? ? ? count++;
? ? ? ? ? ? ? ? dialog.dismiss();


? ? ? ? ? ? }
? ? ? ? });
// ? ? ? ? ? ? ? ?打开相册
? ? ? ? tv3.setOnClickListener(new View.OnClickListener() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void onClick(View v) {
// ? ? ? ? ? ? ? ?pickPhoto();
// ? ? ? ? ? ? ? ?count++;
// ? ? ? ? ? ? ? ?startActivity(new Intent(WriteDiaryActivity.this,SelectAlbumActivity.class));
? ? ? ? ? ? ? ? Intent intent=new Intent(WriteDiaryActivity.this,SelectAlbumActivity.class);
? ? ? ? ? ? ? ? startActivityForResult(intent,RESULT_LOAD_IMG);
? ? ? ? ? ? ? ? dialog.dismiss();
? ? ? ? ? ? }
? ? ? ? });
? ? }

? ? //拍照
? ? private void takePhoto() {

? ? ? ? int hasCameraPermission = ContextCompat.checkSelfPermission(getApplication(),
? ? ? ? ? ? ? ? Manifest.permission.CAMERA);
? ? ? ? if (hasCameraPermission == PackageManager.PERMISSION_GRANTED) {
? ? ? ? ? ? //有权限,调起相机拍照。
? ? ? ? ? ? openCamera();
? ? ? ? } else {
? ? ? ? ? ? //没有权限,申请权限。
? ? ? ? ? ? ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},
? ? ? ? ? ? ? ? ? ? PERMISSION_CAMERA_REQUEST_CODE);
? ? ? ? }
? ? }


? ? // ? ?相册
? ? private void pickPhoto() {
? ? ? ? Intent intent=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
? ? ? ? startActivityForResult(intent,RESULT_LOAD_IMG);
? ? }


? ? //当图片被选中的返回结果
? ? @Override
? ? protected void onActivityResult(int requestCode, int resultCode, Intent data) {
? ? ? ? super.onActivityResult(requestCode, resultCode, data);

? ? ? ? try {
? ? ? ? ? ? if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {

? ? ? ? ? ? ? ? if (list.size() == MAX_PHOTO) {

? ? ? ? ? ? ? ? ? ? removeItem();
? ? ? ? ? ? ? ? ? ? refreshAdapter();
? ? ? ? ? ? ? ? ? ? return;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? removeItem();

? ? ? ? ? ? ? ?ArrayList<String> arrayList = data.getStringArrayListExtra("selectPic");
? ? ? ? ? ? ? ?for (int i=0;i<arrayList.size();i++){
? ? ? ? ? ? ? ? ? ?list.add(arrayList.get(i));
? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? refreshAdapter();


? ? ? ? ? ? ? ? list.add("default");
? ? ? ? ? ? ? ? refreshAdapter();
? ? ? ? ? ? }
? ? ? ? }catch (Exception ex){
? ? ? ? ? ? Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show();
? ? ? ? }


? ? ? ? if (requestCode == CAMERA_REQUEST_CODE) {
? ? ? ? ? ? if (resultCode == RESULT_OK) {
? ? ? ? ? ? ? ? if (isAndroidQ) {
? ? ? ? ? ? ? ? ? ? // Android 10 使用图片uri加载
// ? ? ? ? ? ? ? ? ? ?ivHeadPic.setImageURI(mCameraUri);
? ? ? ? ? ? ? ? ? ? removeItem();
? ? ? ? ? ? ? ? ? ? list.add(mCameraUri.toString());
? ? ? ? ? ? ? ? ? ? list.add("default");
? ? ? ? ? ? ? ? ? ? refreshAdapter();
? ? ? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? ? ? // 使用图片路径加载
? ? ? ? ? ? ? ? ? ? removeItem();
? ? ? ? ? ? ? ? ? ? list.add(mCameraImagePath);
? ? ? ? ? ? ? ? ? ? list.add("default");
? ? ? ? ? ? ? ? ? ? refreshAdapter();
// ? ? ? ? ? ? ? ? ? ?ivHeadPic.setImageBitmap(BitmapFactory.decodeFile(mCameraImagePath));
? ? ? ? ? ? ? ? }
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? Toast.makeText(this,"取消",Toast.LENGTH_LONG).show();
? ? ? ? ? ? }
? ? ? ? }
? ? }


? ? /**
? ? ?* 调起相机拍照
? ? ?*/
? ? private void openCamera() {
? ? ? ? Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
? ? ? ? // 判断是否有相机
? ? ? ? if (captureIntent.resolveActivity(getPackageManager()) != null) {
? ? ? ? ? ? File photoFile = null;
? ? ? ? ? ? Uri photoUri = null;

? ? ? ? ? ? if (isAndroidQ) {
? ? ? ? ? ? ? ? // 适配android 10
? ? ? ? ? ? ? ? photoUri = createImageUri();
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? photoFile = createImageFile();
? ? ? ? ? ? ? ? } catch (IOException e) {
? ? ? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? if (photoFile != null) {
? ? ? ? ? ? ? ? ? ? mCameraImagePath = photoFile.getAbsolutePath();
? ? ? ? ? ? ? ? ? ? if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
? ? ? ? ? ? ? ? ? ? ? ? //适配Android 7.0文件权限,通过FileProvider创建一个content类型的Uri
? ? ? ? ? ? ? ? ? ? ? ? photoUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", photoFile);
? ? ? ? ? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? ? ? ? ? photoUri = Uri.fromFile(photoFile);
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }

? ? ? ? ? ? mCameraUri = photoUri;
? ? ? ? ? ? if (photoUri != null) {
? ? ? ? ? ? ? ? captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
? ? ? ? ? ? ? ? captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
? ? ? ? ? ? ? ? startActivityForResult(captureIntent, CAMERA_REQUEST_CODE);
? ? ? ? ? ? }
? ? ? ? }
? ? }

? ? /**
? ? ?* 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
? ? ?*
? ? ?* @return 图片的uri
? ? ?*/
? ? private Uri createImageUri() {
? ? ? ? String status = Environment.getExternalStorageState();
? ? ? ? // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
? ? ? ? if (status.equals(Environment.MEDIA_MOUNTED)) {
? ? ? ? ? ? return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
? ? ? ? } else {
? ? ? ? ? ? return getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
? ? ? ? }
? ? }

? ? /**
? ? ?* 创建保存图片的文件
? ? ?* @return
? ? ?* @throws IOException
? ? ?*/
? ? private File createImageFile() throws IOException {
? ? ? ? String imageName = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
? ? ? ? File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
? ? ? ? if (!storageDir.exists()) {
? ? ? ? ? ? storageDir.mkdir();
? ? ? ? }
? ? ? ? File tempFile = new File(storageDir, imageName);
? ? ? ? if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
? ? ? ? ? ? return null;
? ? ? ? }
? ? ? ? return tempFile;
? ? }
? ? /**
? ? ?* 处理权限申请的回调。
? ? ?*
? ? ?* @param requestCode
? ? ?* @param permissions
? ? ?* @param grantResults
? ? ?*/
? ? @Override
? ? public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
? ? ? ? if (requestCode == PERMISSION_CAMERA_REQUEST_CODE) {
? ? ? ? ? ? if (grantResults.length > 0
? ? ? ? ? ? ? ? ? ? && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
? ? ? ? ? ? ? ? //允许权限,有调起相机拍照。
? ? ? ? ? ? ? ? openCamera();
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? //拒绝权限,弹出提示框。
? ? ? ? ? ? ? ? Toast.makeText(this,"拍照权限被拒绝",Toast.LENGTH_LONG).show();
? ? ? ? ? ? }
? ? ? ? }
? ? }
? ? /**
? ? ?* ????* 刷新视图
? ? ?* <p>
? ? ?* ???
? ? ?*/

? ? private void refreshAdapter() {

? ? ? ? if (list == null) {

? ? ? ? ? ? list = new ArrayList<String>();

? ? ? ? }

? ? ? ? if (itemAdapter == null) {

? ? ? ? ? ? itemAdapter = new WriteDairyAdapter(list, WriteDiaryActivity.this);

? ? ? ? }

? ? ? ? if (list.size() == MAX_PHOTO) {

? ? ? ? ? ? list.remove(list.size() - 1);

? ? ? ? }

? ? ? ? itemAdapter.notifyDataSetChanged();

? ? }

? ? private void removeItem() {

? ? ? ? if (list.size() - 1 != MAX_PHOTO) {

? ? ? ? ? ? if (list.size() != 0) {//删除默认图片

? ? ? ? ? ? ? ? list.remove(list.size() - 1);

? ? ? ? ? ? }

? ? ? ? }

? ? }

? ??
}

3、添加image-loader

implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'

4.添加权限

<uses-permission android:name="android.permission.INTERNET"/>
? ? <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

?

?

?

?

?

?

5.适配器以及布局文件可以看?https://download.csdn.net/download/qq_35038014/12633795

软件
前端设计
程序设计
Java相关