Android 实现图片相册选择+拍照,并在选中的图片右上角添加删除图标。

导读:本篇文章讲解 Android 实现图片相册选择+拍照,并在选中的图片右上角添加删除图标。,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

效果图:

Android 实现图片相册选择+拍照,并在选中的图片右上角添加删除图标。

 一、在app的build中引入相应的框架

//recyclerview
implementation "androidx.recyclerview:recyclerview:1.1.0"
//glide
implementation "com.github.bumptech.glide:glide:4.10.0"
implementation "com.github.bumptech.glide:compiler:4.10.0"
//导入相册多图片选择库
implementation 'com.github.donkingliang:ImageSelector:2.1.1'
//压缩文件,压缩图片,压缩Bitmap
implementation 'com.github.nanchen2251:CompressHelper:1.0.5'

2. 对图片进行压缩处理 ImageCompressUtil

package com.ruidde.csndresourcedemo.unilt;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 对图片进行压缩处理
 */
public class ImageCompressUtil {
    /**
     * 通过压缩图片的尺寸来压缩图片大小,仅仅做了缩小,如果图片本身小于目标大小,不做放大操作
     *
     * @param pathName     图片的完整路径
     * @param targetWidth  缩放的目标宽度
     * @param targetHeight 缩放的目标高度
     * @return 缩放后的图片
     */
    public static Bitmap compressBySize(String pathName, int targetWidth, int targetHeight) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        // 不去真的解析图片,只是获取图片的头部信息,包含宽高等;
        Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);
        // 得到图片的宽度、高度;
        int imgWidth = opts.outWidth;
        int imgHeight = opts.outHeight;
        // 分别计算图片宽度、高度与目标宽度、高度的比例;取大于等于该比例的最小整数;
        int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
        int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
        if (widthRatio > 1 || heightRatio > 1) {
            if (widthRatio > heightRatio) {
                opts.inSampleSize = widthRatio;
            } else {
                opts.inSampleSize = heightRatio;
            }
        }
        // 设置好缩放比例后,加载图片进内容;
        opts.inJustDecodeBounds = false;
        opts.inPreferredConfig = Bitmap.Config.RGB_565;
        opts.inDither = true;

        bitmap = BitmapFactory.decodeFile(pathName, opts);
        return bitmap;
    }

}

3.选中图片的Adapter:PhotoImagsAdapter

package com.ruidde.csndresourcedemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.nanchen.compresshelper.CompressHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

class PhotoImagsAdapter extends RecyclerView.Adapter<PhotoImagsAdapter.InfoImageHolder> {

    private Context context;
    private List<String> mDatas = new ArrayList<>();

    public PhotoImagsAdapter(Context context, List<String> mDatas) {
        this.context = context;
        this.mDatas = mDatas;
    }

    public void setmDatas(List<String> mDatas) {
        this.mDatas = mDatas;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public PhotoImagsAdapter.InfoImageHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.item_info_img, parent, false);
        return new InfoImageHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull InfoImageHolder holder, final int position) {
        /**
         * 数据操作
         */
        if (mDatas != null && mDatas.size() > 0) {
            if (mDatas.size() == position) {
                holder.img_photo.setImageResource(R.mipmap.img_add);
                holder.btn_clearResource.setVisibility(View.GONE);
            } else {
                String dateStr = mDatas.get(position);
                holder.btn_clearResource.setVisibility(View.VISIBLE);
                /**
                 * 在Activity里面使用
                 * dateStr 图片的绝对路径
                 * */
                File oldFile = new File(dateStr);
//                File newFile = CompressHelper.getDefault(this).compressToFile(oldFile);
//                File newFile = new CompressHelper.Builder(context)
//                        .setMaxWidth(360)  // 默认最大宽度为720
//                        .setMaxHeight(480) // 默认最大高度为960
//                        .setQuality(80)    // 默认压缩质量为80
//                        .setCompressFormat(Bitmap.CompressFormat.JPEG) // 设置默认压缩为jpg格式
//                        .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory("Aruidde").getAbsolutePath()) //压缩图片所在路径
//                        .build()
//                        .compressToFile(oldFile);
                /**
                 * 但是不会存储压缩后的图片
                 * 压缩后的Bitmap
                 * */
//                Bitmap bitmap = CompressHelper.getDefault(context).compressToBitmap(oldFile);
                Bitmap bitmap = new CompressHelper.Builder(context)
                        .setMaxWidth(360)  // 默认最大宽度为720
                        .setMaxHeight(480) // 默认最大高度为960
                        .build()
                        .compressToBitmap(oldFile);

                /**
                 * 适合API 28
                 * 将图片压缩并转化为Bitmap
                 * */
//                Bitmap arrBitmap = ImageCompressUtil.compressBySize(dateStr, 300, 300);
//                Glide.with(context).load(newFile).into(holder.img_photo);
                Glide.with(context).load(bitmap).into(holder.img_photo);
            }
        } else {
            holder.img_photo.setImageResource(R.mipmap.img_add);
            holder.btn_clearResource.setVisibility(View.GONE);
        }


        //添加图片
        holder.img_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                itemOnClickListener.onAddItenClick(position);
            }
        });
        //删除图片
        holder.btn_clearResource.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                itemOnClickListener.onDeleteItenClick(position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mDatas != null ? (mDatas.size() + 1) : 1;
    }

    /**
     * 创建ViewHolder
     * 元素声明
     */
    class InfoImageHolder extends RecyclerView.ViewHolder {

        ImageView img_photo;
        ImageView btn_clearResource;
        RelativeLayout re_imgResourxe;

        public InfoImageHolder(@NonNull View itemView) {
            super(itemView);
            img_photo = itemView.findViewById(R.id.img_photo);
            btn_clearResource = itemView.findViewById(R.id.btn_clearResource);
            re_imgResourxe = itemView.findViewById(R.id.re_imgResourxe);
        }
    }

    //添加图片
    private InfoImgClickListener itemOnClickListener;

    interface InfoImgClickListener {
        void onAddItenClick(int addPosition);

        void onDeleteItenClick(int deletePosition);
    }

    public void setAddImgClickLisitenner(InfoImgClickListener itemOnClickListener) {
        this.itemOnClickListener = itemOnClickListener;
    }
}

4.布局xml

(1)。item_info_img

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:id="@+id/re_imgResourxe"
        android:layout_centerVertical="true"
        android:visibility="visible"
        android:layout_width="235px"
        android:layout_height="235px">

        <ImageView
            android:id="@+id/img_photo"
            android:layout_width="200px"
            android:layout_height="200px"
            android:layout_centerInParent="true"
            android:scaleType="fitXY"
            android:src="@mipmap/img_add"/>

        <ImageView
            android:id="@+id/btn_clearResource"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/img_exit"
            android:padding="10px"
            android:layout_marginTop="-10px"
            android:layout_marginRight="-10px"
            android:layout_alignParentRight="true"/>

    </RelativeLayout>

</RelativeLayout>

(2)。主Activity布局

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/img_recycleview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
    app:spanCount="4"
    tools:listitem="@layout/item_info_img"/>

5.最主要通过 FileProvider 创建共享文件

在res文件夹下创建xml文件并创建 file_paths.xml文件

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <paths>
        <external-path name="images" path="Pictures" />
        <external-path path="jzFile" name="image" />
        <external-files-path name="jzApp.apk" path="Download"/>
    </paths>
</paths>

Mainfest文件中添加注册

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="com.ruidde.csndresourcedemo.fileProvider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

具体Demo

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/119123.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!