0

I have a framelayout. it includes a button. At runtime I click the button to pick an image from the gallery.

I create a imageView ,set the chosen image from the gallery on the imageView and add the imageView to framelayout.

then i save the entire view(framelayout) as a bitmap. But the saved bitmap only shows the button and a black screen where the imageView should be.

I tried a lot of ways but could not resolve it...

pls help

public class MainActivity extends AppCompatActivity {

Button b;
RelativeLayout frame;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b = (Button) findViewById(R.id.b);
    frame = (RelativeLayout) findViewById(R.id.frame);

    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, 1);
        }
    });
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode){
        case 1 :
            Uri selectedImage = data.getData();
              try {
                bitmap = MediaStore.Images.Media.getBitmap(
                        MainActivity.this.getContentResolver(), selectedImage);
            } catch (IOException e) {
                e.printStackTrace();
            }





            ImageView i = new ImageView(MainActivity.this);
            i.setImageBitmap(bitmap);

            frame.addView(i);
            frame.invalidate();


           Bitmap bitmapFromView = Bitmap.createBitmap(frame.getWidth(),frame.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvass = new Canvas(bitmapFromView);
            frame.draw(canvass);
            saveBitmap(bitmapFromView);


            break;
    }

}


public void saveBitmap(Bitmap bitmap) {
    File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(imagePath);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        Log.e("GREC", e.getMessage(), e);
    } catch (IOException e) {
        Log.e("GREC", e.getMessage(), e);
    }

    MediaScannerConnection.scanFile(getApplicationContext(),
            new String[]{imagePath.getAbsolutePath()}, null,
            new MediaScannerConnection.OnScanCompletedListener() {

                @Override
                public void onScanCompleted(String path, Uri uri) {
                    // TODO Auto-generated method stub

                }
            });
}




 /*
 also tried this...not working

public static Bitmap loadBitmapFromView(View v) {
    Bitmap bitmap;
    v.setDrawingCacheEnabled(true);
    bitmap = Bitmap.createBitmap(v.getDrawingCache());
    v.setDrawingCacheEnabled(false);
    return bitmap;
   }

    */

}
DAVE
  • 125
  • 1
  • 10
  • To correctly save the framelayout's contents into a bitmap, refer this: http://stackoverflow.com/questions/30196965/how-to-take-a-screenshot-of-current-activity-and-then-share-it – dangling_refrenz Apr 04 '17 at 21:13

2 Answers2

0

Now finally i made a code working in most of the device i had tested

1) MainActivity.class

public class MainActivity extends AppCompatActivity {

    private final int SELECT_PHOTO = 2;
    private ImageView contactimage;
    private LinearLayout content;
    private TextView textall;

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

        content = (LinearLayout) findViewById(R.id.frame_save);


        contactimage = (ImageView) findViewById(R.id.contactimage);

        textall = (TextView) findViewById(R.id.textall);

        textall.setText("MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst\n" +
                "         MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst\n" +
                "          MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst\n" +
                "           MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst MY TEst\n" +
                "            MY TEst MY TEst MY TEst MY TEst MY TEst");


        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, SELECT_PHOTO);
    }


    @Override
    public void onActivityResult(int reqCode, int resultCode, Intent data) {
        super.onActivityResult(reqCode, resultCode, data);

        switch (reqCode) {
            case SELECT_PHOTO:
                if (resultCode == RESULT_OK) {

                    try {
                        final Uri imageUri = data.getData();
                        final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                        final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                        contactimage.setImageBitmap(selectedImage);

                        try {
                            content.setDrawingCacheEnabled(true);

                            content.setDrawingCacheEnabled(true);

                            content.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

                            content.layout(0, 0, content.getMeasuredWidth(), content.getMeasuredHeight());

                            content.buildDrawingCache(true);
                            Bitmap bitmap = getBitmapFromView(content);
                            content.setDrawingCacheEnabled(false);

                            File file, f = null;
                            if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
                                file = new File(android.os.Environment.getExternalStorageDirectory(), "Handcare");
                                if (!file.exists()) {
                                    file.mkdirs();

                                }
                                f = new File(file.getAbsolutePath() + File.separator + "MyImage.png");
                            }
                            FileOutputStream ostream = new FileOutputStream(f);
                            bitmap.compress(Bitmap.CompressFormat.PNG, 10, ostream);
                            ostream.close();


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

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

                }
        }
    }


    private Bitmap getBitmapFromView(View view) {
        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(returnedBitmap);
        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null) {
            bgDrawable.draw(canvas);
        } else {
            canvas.drawColor(Color.WHITE);
        }
        view.draw(canvas);
        return returnedBitmap;
    }
}

2) activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".MainActivity"
    android:background="@android:color/white">

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical"
       android:id="@+id/frame_save">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/black"
        android:id="@+id/textall"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/contactimage"
        android:layout_margin="10dp"/>

   </LinearLayout>
</LinearLayout>

3) In manifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Abhay Dhiman
  • 131
  • 1
  • 6
  • I already tried this method to save. Plus I don't see any reason to change my FrameLayout to LinearLayout. Still I tried with Linear and Relative- still same – DAVE May 02 '16 at 12:10
  • Can you tell me your device config ?I had tried this code in so much device and its working well let me try some other to ,as i had use this code in custom dialog – Abhay Dhiman May 02 '16 at 17:04
  • Try putting your code in onActivityResult()... As u can see I am calling saveBitmap(); from onActivityResult() But if i call saveBitmap() via a buton click it works fine.. I am wondering if something is related to overall flow of the code .. – DAVE May 03 '16 at 05:59
  • @DAVE i had posted a new code try this its working in all device – Abhay Dhiman May 04 '16 at 07:25
0

I did it.

I WAS ADDING THE IMAGE AND SAVING IT SEQUENTIALLY IN onActivityResult();

this:

        ImageView i = new ImageView(MainActivity.this);
        i.setImageBitmap(bitmap);
        frame.addView(i);
        frame.invalidate();

and this:

        Bitmap bitmapFromView =   Bitmap.createBitmap(frame.getWidth(),frame.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvass = new Canvas(bitmapFromView);
        frame.draw(canvass);
        saveBitmap(bitmapFromView);

It seems that although the added image was visible to me on device but internally android had not processed it.And before that that could happen I was trying to save the view.

Now I finally solved it by adding the the imageView in onActivityResult(); and saving this view on a separate button click.

I also got positive result when I fired a worker thread which would sleep for 1 second after adding the imageview. Then in postExecute() of the worker thread I saved the view as bitmap.

DAVE
  • 125
  • 1
  • 10