0

I have two Image-View in a layout, one as at background and another is above that(at foreground) and I want to save both the images. So can anyone help me out that how can I save both the images into the device storage as single image.

Thank you.

  • 1
    Welcome to SO. Please have a look on [how to ask](https://stackoverflow.com/help/how-to-ask) your question and provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – CIAndrews Apr 03 '19 at 13:18

1 Answers1

1

A simple solution I found here is to put both of your imageView in a single Layout and then save your layout as a Bitmap. I will retype the solution code here

private Bitmap getBitmap(View v) {
v.clearFocus();
v.setPressed(false);

boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);

// Reset the drawing cache background color to fully transparent
// for the duration of this operation
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);

if (color != 0) {
    v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
    Toast.makeText(StopWarApp.getContext(), "Something went wrong",
            Toast.LENGTH_SHORT).show();
    return null;
}

Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

// Restore the view
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);

return bitmap;

}

Now that you have your Bitmap, you can save it to your storage like this

  private void saveImage(Bitmap finalBitmap, String image_name) {

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root);
    myDir.mkdirs();
    String fname = "Image-" + image_name+ ".jpg";
    File file = new File(myDir, fname);
    if (file.exists()) file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Don't forget to add your permissions in the manifest file

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Amine
  • 2,241
  • 2
  • 19
  • 41