钢镚儿冲刺一周期第九天

一、说在前面

  昨天完成了图片的读取,遇到的问题有很多。不过都解决了,今天干了一天的活都忘掉了,就应该遇到一个bug截个图。T_T

  今天把图片的褪色和将自己的功能加到团队的项目里面。

二、思路

  将图片褪色的功能对接到读取图片出来的界面后面,对读出来的图片进行处理。和队友一起商量着把我的功能加到哪里。

三、代码

package com.example.imgpicker;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.imgpicker.Adapter.ResultImageAdapter;
import com.example.imgpicker.domain.ImageItem;
import com.example.imgpicker.utils.PickerConfig;

import java.lang.ref.WeakReference;
import java.util.List;

@RequiresApi(api = Build.VERSION_CODES.M)
public class MainActivity extends AppCompatActivity implements PickerConfig.OnImageSelectFinishListener {
    private static final int MAX_SELECTED_COUNT = 1;
    private static final String TAG = "MainActivity";
    private static final int PERMISSION_REQUEST_CODE = 1;
    RecyclerView result_list;
    ResultImageAdapter resultImageAdapter;
    ImageView last_iv;

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

    }

    private void initView() {
        result_list = findViewById(R.id.result_list);
        last_iv =findViewById(R.id.last_iv);
        resultImageAdapter = new ResultImageAdapter();
        result_list.setAdapter(resultImageAdapter);

    }

    private void initPickerConfig() {
        PickerConfig picker=PickerConfig.getInstance();
        //设置最大值
        picker.setMaxSelectedCount(MAX_SELECTED_COUNT);
        picker.setOnImageSelectFinishListener(this);
    }


    private void checkPermission() {
        int readExStoragePermissionRest = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
        if (readExStoragePermissionRest!= PackageManager.PERMISSION_GRANTED){
            //没有权限
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},PERMISSION_REQUEST_CODE);

        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==PERMISSION_REQUEST_CODE){
            if (grantResults.length==0&&grantResults[0]== PackageManager.PERMISSION_GRANTED) {
                //有权限

            }else {
                //没有权限
                //根据交互去处理

            }
        }
    }

    public void pickImgs(View view){
        // 打开另外一个界面
        startActivity(new Intent(this,PickerAvtivity.class));
    }

    @Override
    public void onSelectedFinished(List<ImageItem> result) {

        //返回来的数据显示出来
        for (ImageItem imageItem : result) {
            Log.d(TAG, " item----> "+imageItem);
        }
        int horizentalCount;
        if(result.size()<3){
            horizentalCount=result.size();
        }else {
            horizentalCount=3;
        }
        ImageItem i=result.get(0);
        func(i.getPath(),i.getW(),i.getH());

    }

    //褪色处理
    public void func(String path,int w,int h)
    {

        Bitmap bitmap = convertToBitmap(path,w,h);
//        int width = bitmap.getWidth();
//        int height = bitmap.getHeight();
        Bitmap base = bitmap.copy(Bitmap.Config.ARGB_8888, true);
//        Bitmap B=toGrayscale(base);
        Canvas canvas = new Canvas(base);//以base为模板创建canvas对象
        canvas.drawBitmap(bitmap, new Matrix(),new Paint());
        for(int i = 0; i < base.getWidth(); i++)//遍历像素点
        {
            for(int j = 0; j < base.getHeight()*0.5; j++)
            {
                int color = bitmap.getPixel(i, j);

                int r = Color.red(color);
                int g = Color.green(color);
                int b = Color.blue(color);
                int a = Color.alpha(color);

                int avg = (r+g+b)/3;//RGB均值

                r= (int) (r/3);
                g=(int)(g/3);
                b=(int)(b/3);
                base.setPixel(i, j,Color.argb(a, r, g, b));
//                if(avg >= 100)//100可以理解为经验值
//                {
//                    base.setPixel(i, j,Color.argb(a, 255, 255, 255));//设为白色
//                }
//                else
//                {
//                    base.setPixel(i, j,Color.argb(a, 0, 0, 0));//设为黑色
//                }
            }
        }
        bitmap.recycle();
        last_iv.setImageBitmap(base);
    }
    public static Bitmap convertToBitmap(String path, int w, int h) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        // 设置为ture只获取图片大小
        opts.inJustDecodeBounds = true;
        opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
        // 返回为空
        BitmapFactory.decodeFile(path, opts);
        int width = opts.outWidth;
        int height = opts.outHeight;
        float scaleWidth = 0.f, scaleHeight = 0.f;
        if (width > w || height > h) {
            // 缩放
            scaleWidth = ((float) width) / w;
            scaleHeight = ((float) height) / h;
        }
        opts.inJustDecodeBounds = false;
        float scale = Math.max(scaleWidth, scaleHeight);
        opts.inSampleSize = (int)scale;
        WeakReference<Bitmap> weak = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts));
        return Bitmap.createScaledBitmap(weak.get(), w, h, true);
    }
}
MainActivity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="wrap_content"
            android:id="@+id/back_press_iv"
            android:src="@mipmap/pick_black_back"
            android:padding="10dp"
            android:layout_height="wrap_content"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_centerVertical="true"
            android:id="@+id/finish_tv"
            android:layout_alignParentRight="true"
            android:layout_marginRight="10dp"
            android:text="(0/1)完成"
            android:textColor="#000000"
            android:layout_height="wrap_content"/>

    </RelativeLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:id="@+id/image_list_view"
        android:layout_height="match_parent"/>

</LinearLayout>
activity_picker
package com.example.imgpicker.Adapter;

import android.graphics.Point;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

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

import com.bumptech.glide.Glide;
import com.example.imgpicker.R;
import com.example.imgpicker.domain.ImageItem;
import com.example.imgpicker.utils.SizeUtils;

import java.util.ArrayList;
import java.util.List;

public class ResultImageAdapter extends RecyclerView.Adapter<ResultImageAdapter.InnerHolder> {

    private List<ImageItem>  mImageItems=new ArrayList<>();
    private int horizentalCount=1;


    @NonNull
    @Override
    public ResultImageAdapter.InnerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image, parent, false);
        itemView.findViewById(R.id.image_check_box).setVisibility(View.GONE);

        return new InnerHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull ResultImageAdapter.InnerHolder holder, int position) {
        View itemView = holder.itemView;
        Point point = SizeUtils.getScreenSize(itemView.getContext());
        RecyclerView.LayoutParams layoutParams=new RecyclerView.LayoutParams(point.x/horizentalCount,point.x/horizentalCount);
        itemView.setLayoutParams(layoutParams);
        ImageView imageView =itemView.findViewById(R.id.image_iv);
        ImageItem imageItem = mImageItems.get(position);
        Glide.with(imageView.getContext()).load(imageItem.getPath()).into(imageView);
    }

    @Override
    public int getItemCount() {
        return mImageItems.size();
    }

    public void setData(List<ImageItem> result, int horizentalCount) {
        this.horizentalCount=horizentalCount;
        mImageItems.clear();
        mImageItems.addAll(result);
        notifyDataSetChanged();
    }

    public class InnerHolder extends RecyclerView.ViewHolder {
        public InnerHolder(@NonNull View itemView) {
            super(itemView);
        }
    }



}
Result_Manager
package com.example.imgpicker;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.CursorLoader;
import androidx.loader.content.Loader;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.imgpicker.Adapter.ImageListAdapter;
import com.example.imgpicker.domain.ImageItem;
import com.example.imgpicker.utils.PickerConfig;

import java.util.ArrayList;
import java.util.List;

//D/PickerAvtivity: onCreate: ====================================
//D/PickerAvtivity: _id  ====  43
//D/PickerAvtivity: _data  ====  /storage/emulated/0/DCIM/Camera/IMG_20200420_064425.jpg
//D/PickerAvtivity: _size  ====  197214
//D/PickerAvtivity: _display_name  ====  IMG_20200420_064425.jpg
//D/PickerAvtivity: mime_type  ====  image/jpeg
//D/PickerAvtivity: title  ====  IMG_20200420_064425
//D/PickerAvtivity: date_added  ====  1587365066
//D/PickerAvtivity: date_modified  ====  1587365066
//D/PickerAvtivity: description  ====  null
//D/PickerAvtivity: picasa_id  ====  null
//D/PickerAvtivity: isprivate  ====  null
//D/PickerAvtivity: latitude  ====  37.422
//D/PickerAvtivity: longitude  ====  -122.084
//D/PickerAvtivity: datetaken  ====  1587365065974
//D/PickerAvtivity: orientation  ====  0
//D/PickerAvtivity: mini_thumb_magic  ====  null
//D/PickerAvtivity: bucket_id  ====  -1739773001
//D/PickerAvtivity: bucket_display_name  ====  Camera
//D/PickerAvtivity: width  ====  960
//D/PickerAvtivity: height  ====  1280
//D/PickerAvtivity: onCreate: ====================================

public class PickerAvtivity extends AppCompatActivity implements ImageListAdapter.OnItemSelectedChangeListener {

    private static final String TAG = "PickerAvtivity";
    public static final int LOADER_ID=1;

    private List<ImageItem> mImageItem=new ArrayList<>();
    ImageListAdapter mImageListAdapter;
    TextView finishView;
    PickerConfig picker;
    ImageView backView;

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

//        ContentResolver contentResolver=getContentResolver();
//        Uri imageUri= MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
//        Cursor query =contentResolver.query(imageUri,null,null,null,null);
//        String[] colunmNames=query.getColumnNames();
//        while (query.moveToNext()){
//            Log.d(TAG, "onCreate: ====================================");
//            for (String colunmName : colunmNames) {
//                Log.d(TAG, colunmName+"  ====  "+query.getString(query.getColumnIndex(colunmName)));
//            }
//            Log.d(TAG, "onCreate: ====================================");
//        }
//        query.close();

        initLoaderManager();
        initView();
        initEvent();
        initConfig();
    }

    private void initConfig() {
        picker = PickerConfig.getInstance();
        int maxSelectedCount= picker.getMaxSelectedCount();
        mImageListAdapter.setmMaxSelectedCount(maxSelectedCount);

    }

    private void initEvent() {
        mImageListAdapter.setOnItemSelectedChangeListener(this);
        finishView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取所选择的数据
                List<ImageItem> results = mImageListAdapter.getmSelectedItems();
                //通知其他地方
                PickerConfig.OnImageSelectFinishListener onImageSelectFinishListener = picker.getmImageSelectedFinishListener();
                if (onImageSelectFinishListener!=null){
                    onImageSelectFinishListener.onSelectedFinished(results);
                }
                //结束
                finish();
            }
        });
        backView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    private void initView() {
        finishView = findViewById(R.id.finish_tv);
        RecyclerView listView=findViewById(R.id.image_list_view);
        backView = findViewById(R.id.back_press_iv);
        listView.setLayoutManager(new GridLayoutManager(this,3));
        //设置适配器
        mImageListAdapter = new ImageListAdapter();
        listView.setAdapter(mImageListAdapter);


    }

    private void initLoaderManager() {
        mImageItem.clear();
        LoaderManager loaderManager=LoaderManager.getInstance(this);
        loaderManager.initLoader(LOADER_ID, null, new LoaderManager.LoaderCallbacks<Cursor>() {
            @NonNull
            @Override
            public Loader<Cursor> onCreateLoader(int id, @Nullable Bundle args) {
                if(id==LOADER_ID){
                    return new CursorLoader(PickerAvtivity.this,MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            new String[]{"_data","_display_name","date_added","_id","width","height"},
                            null,null,"date_added DESC");
                }
                return null;

            }

            @Override
            public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor cursor) {
                if (cursor!=null){

                    while (cursor.moveToNext()){

                        String path=cursor.getString(0);
                        String title=cursor.getString(1);
                        long date=cursor.getLong(2);
                        int id=cursor.getInt(3);
                        int w=cursor.getInt(4);
                        int h=cursor.getInt(5);
                        ImageItem imageItem=new ImageItem(path,title,date,id,w,h);
//                        func(imageItem);
                        mImageItem.add(imageItem);

                    }
                    cursor.close();
                    for (ImageItem imageItem : mImageItem) {
                        Log.d(TAG, "imageItem  ==========> "+imageItem.toString());
                    }

                    mImageListAdapter.setData(mImageItem);


                }

            }

            @Override
            public void onLoaderReset(@NonNull Loader<Cursor> loader) {

            }
        });



    }

    @Override
    public void OnItemSelectedChange(List<ImageItem> mSelectedItems) {
        //所选择的数据发生变化
        finishView.setText("("+mSelectedItems.size()+"/"+mImageListAdapter.getmMaxSelectedCount()+")完成");

    }

    public void func(ImageView view)
    {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),43);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Bitmap base = Bitmap.createBitmap(width, height,bitmap.getConfig());
//        Bitmap B=toGrayscale(base);
        Canvas canvas = new Canvas(base);//以base为模板创建canvas对象
        canvas.drawBitmap(bitmap, new Matrix(),new Paint());

        for(int i = 0; i < width; i++)//遍历像素点
        {
            for(int j = 0; j < height*0.5; j++)
            {
                int color = bitmap.getPixel(i, j);

                int r = Color.red(color);
                int g = Color.green(color);
                int b = Color.blue(color);
                int a = Color.alpha(color);

                int avg = (r+g+b)/3;//RGB均值

                if(avg >= 150)//100可以理解为经验值
                {
                    base.setPixel(i, j,Color.argb(a, 255, 255, 255));//设为白色
                }
                else
                {
                    base.setPixel(i, j,Color.argb(a, 0, 0, 0));//设为黑色
                }
            }
        }
        bitmap.recycle();
        view.setImageBitmap(base);
    }

}
ImagePicker

四、效果

 

 

 

 

 

 五、感想

  看上去简单的东西往往实现起来会遇到没遇到过的困难,刚开始是有点想当然了,不过在我的坚持下还是攻克了一个又一个的bug,虽然很累,但还是很有成就感。今天就先到这里,明天继续加油!

posted @ 2020-04-26 23:35  酸奶面包  阅读(134)  评论(0编辑  收藏  举报