Как получить доступ к изображению галереи из MainActivity к другому действию (редактору действий)? - PullRequest
0 голосов
/ 16 апреля 2020

Я пишу приложение-редактор фильтров, как и приложение-фильтр Instagram, я хочу загрузить изображение из галереи из кнопки галереи. Галерея открывается с выбранным изображением, затем вместо загрузки в Main2Activity отображается «загрузка слева 1».

    public class MainActivity extends AppCompatActivity {

    ImageButton image_open;
    public static final int PERMISSION_PICK_IMAGE=1000;
    Bitmap originalBitmap,filteredBitmap,finalBitmap;
    ImageView img_preview;

     FilterListFragment filterListFragment;
     EditImageFragment editImageFragment;


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

    image_open=(ImageButton) findViewById(R.id.action_display);


    image_open.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openImageFromGallery();
        }
    });

     }



     private void openImage(String path) {
    Intent intent =new Intent(MainActivity.this,com.example.instatest.Main2Activity.class);
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse(path),"image/*");
    startActivity(intent);

       }



     private void openImageFromGallery() {
    Dexter.withActivity(this).withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .withListener(new MultiplePermissionsListener() {
                @Override
                public void onPermissionsChecked(MultiplePermissionsReport report) {
                    if (report.areAllPermissionsGranted()) {
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType("image/*");
                        startActivityForResult(intent, PERMISSION_PICK_IMAGE);
                    } else {
                        Toast.makeText(MainActivity.this, "Permissions denied!", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, 
   PermissionToken token) {
                    token.continuePermissionRequest();
                }
            }).check();
    }


     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK && requestCode == PERMISSION_PICK_IMAGE) {
        Bitmap bitmap = BitmapUtils.getBitmapFromGallery(this, data.getData(), 800, 800);

        // clear bitmap memory
        originalBitmap.recycle();
        finalBitmap.recycle();
        filteredBitmap.recycle();

        originalBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        finalBitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
        filteredBitmap= originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
        img_preview.setImageBitmap(originalBitmap);
        bitmap.recycle();
        // render selected image thumbnails
        filterListFragment.displayThumbnail(originalBitmap);

    }

    }}

Это Main2Activity:

 public class Main2Activity extends AppCompatActivity implements FiltersListFragmentListener, 
 EditImageFragmentListener {

   public static final String pictureName="flash.jpg";
   public static final int PERMISSION_PICK_IMAGE=1000;

   ImageView img_preview;
   TabLayout tabLayout;
   ViewPager viewPager;
   CoordinatorLayout coordinatorLayout;

   Bitmap originalBitmap,filteredBitmap,finalBitmap;

   FilterListFragment filterListFragment;
   EditImageFragment editImageFragment;

   int brightnessFinal=0;
   float saturationFinal=1.0f;
   float constrantFinal=1.0f;

   //here load native image filter library
   static {
     System.loadLibrary("NativeImageProcessor");
   }


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

    Toolbar toolbar= findViewById(R.id.toolBar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle("Instagram Filter");

    //view
    img_preview=(ImageView) findViewById(R.id.image_preview);
    tabLayout=(TabLayout) findViewById(R.id.tabs);
    viewPager=(ViewPager) findViewById(R.id.viewpager);
    coordinatorLayout=(CoordinatorLayout) findViewById(R.id.coordinator);

    loadImage();

    setupViewPager(viewPager);
    tabLayout.setupWithViewPager(viewPager);
     }




       private void loadImage() {
    originalBitmap= BitmapUtils.getBitmapFromAssets(this,pictureName,300,300);
    filteredBitmap=originalBitmap.copy(Bitmap.Config.ARGB_8888,true);
    finalBitmap=originalBitmap.copy(Bitmap.Config.ARGB_8888,true);
    img_preview.setImageBitmap(originalBitmap);
      }

    private void setupViewPager(ViewPager viewPager) {

    ViewPagerAdapter adapter=new ViewPagerAdapter(getSupportFragmentManager());

    filterListFragment=new FilterListFragment();
    filterListFragment.setListener(this);

    editImageFragment=new EditImageFragment();
    editImageFragment.setListener(this);

    adapter.addFragment(filterListFragment, "Filters");
    adapter.addFragment(editImageFragment, "EDIT");


    viewPager.setAdapter(adapter);

    }


     @Override
     public void onBrightnessChanged(int brightness) {
    brightnessFinal=brightness;
    Filter myFilter=new Filter();
    myFilter.addSubFilter(new BrightnessSubFilter(brightness));


img_preview.setImageBitmap(myFilter.processFilter(finalBitmap.copy(Bitmap.Config.ARGB_8888,true)));
      }

    @Override
   public void onSaturationChanged(float saturation) {
    saturationFinal=saturation;
    Filter myFilter=new Filter();
    myFilter.addSubFilter(new SaturationSubfilter(saturation));
    img_preview.setImageBitmap(myFilter.processFilter(finalBitmap.copy(Bitmap.Config.ARGB_8888,true)));
    }


     @Override
     public void onConstrantChanged(float constrant) {
    constrantFinal=constrant;
    Filter myFilter=new Filter();
    myFilter.addSubFilter(new ContrastSubFilter(constrant));
    img_preview.setImageBitmap(myFilter.processFilter(finalBitmap.copy(Bitmap.Config.ARGB_8888,true)));
      }





    @Override
    public void onEditStarted() {

     }





    @Override
    public void onEditCompleted() {
    Bitmap bitmap=filteredBitmap.copy(Bitmap.Config.ARGB_8888,true);

    Filter myFilter=new Filter();
    myFilter.addSubFilter(new BrightnessSubFilter(brightnessFinal));
    myFilter.addSubFilter(new SaturationSubfilter(saturationFinal));
    myFilter.addSubFilter(new ContrastSubFilter(constrantFinal));

    finalBitmap=myFilter.processFilter(bitmap);
     }


    @Override
    public void onFilterSelected(Filter filter) {
    resetControl();
    filteredBitmap=originalBitmap.copy(Bitmap.Config.ARGB_8888,true);
    img_preview.setImageBitmap(filter.processFilter(filteredBitmap));
    finalBitmap=filteredBitmap.copy(Bitmap.Config.ARGB_8888,true);

     }

    private void resetControl() {
    if(editImageFragment!=null)
        editImageFragment.resetControls();
    brightnessFinal=0;
    saturationFinal=1.0f;
    constrantFinal=1.0f;

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main,menu);
    return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
     int id=item.getItemId();
    if(id==R.id.action_open)
    {
        openImageFromGallery();
        return true;
    }
    if (id == R.id.action_save) {
        saveImageToGallery();
        return true;
    }

    return super.onOptionsItemSelected(item);
    }

     private void saveImageToGallery() {
    Dexter.withActivity(this).withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .withListener(new MultiplePermissionsListener() {
                @Override
                public void onPermissionsChecked(MultiplePermissionsReport report) {
                    if (report.areAllPermissionsGranted()) {

                        try {
                            final String path = BitmapUtils.insertImage(getContentResolver(), finalBitmap,
                                    System.currentTimeMillis() + "_profile.jpg", null);

                            if (!TextUtils.isEmpty(path)) {
                                Snackbar snackbar = Snackbar
                                        .make(coordinatorLayout, "Image saved to gallery!", Snackbar.LENGTH_LONG)
                                        .setAction("OPEN", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                openImage(path);
                                            }
                                        });

                                snackbar.show();

                            }

                            else {
                                Snackbar snackbar = Snackbar
                                        .make(coordinatorLayout, "Unable to save image!", Snackbar.LENGTH_LONG);

                                snackbar.show();
                            }

                        }catch (IOException e) {
                            e.printStackTrace();
                        }


                    } else {
                        Toast.makeText(Main2Activity.this, "Permissions are not granted!", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                    token.continuePermissionRequest();
                }
            }).check();
     }

    private void openImage(String path) {
    Intent intent =new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse(path),"image/*");
    startActivity(intent);

    }

    private void openImageFromGallery() {
    Dexter.withActivity(this).withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, 
             Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .withListener(new MultiplePermissionsListener() {
                @Override
                public void onPermissionsChecked(MultiplePermissionsReport report) {
                    if (report.areAllPermissionsGranted()) {
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType("image/*");
                        startActivityForResult(intent, PERMISSION_PICK_IMAGE);
                    } else {
                        Toast.makeText(Main2Activity.this, "Permissions denied!", 
                        Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, 
                    PermissionToken token) {
                    token.continuePermissionRequest();
                }
            }).check();
      }

     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK && requestCode == PERMISSION_PICK_IMAGE ) {
        Bitmap bitmap = BitmapUtils.getBitmapFromGallery(this, data.getData(), 800, 800);

        // clear bitmap memory
        originalBitmap.recycle();
        finalBitmap.recycle();
        filteredBitmap.recycle();

        originalBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        finalBitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
        filteredBitmap= originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
        img_preview.setImageBitmap(originalBitmap);
        bitmap.recycle();

        // render selected image thumbnails
        filterListFragment.displayThumbnail(originalBitmap);
      }
    }}

Activity_main. xml

 <LinearLayout 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"
    android:clickable="true"
    android:gravity="center"
    tools:context=".MainActivity">


    <ImageButton
        android:id="@+id/action_display"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/gallery_open"
        android:orderInCategory="100"
        android:enabled="true"
        />
  </LinearLayout>

Activity2main. xml

 <android.support.design.widget.CoordinatorLayout 
    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:id="@+id/coordinator"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Main2Activity">


    <android.support.design.widget.AppBarLayout
         android:theme="@style/AppTheme.AppBarOverlay"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         tools:ignore="MissingConstraints">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolBar"
            android:background="@android:color/white"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"></android.support.v7.widget.Toolbar>

       </android.support.design.widget.AppBarLayout>


     <include layout="@layout/content_main"/>

   </android.support.design.widget.CoordinatorLayout>

Где я хочу разместить изображение этого из mainactivity введите описание изображения здесь

...