Get & Save Bitmap From Any UI | Android Studio | Java

Atif Pervaiz
4 min readJan 19, 2023

--

In this article, we will learn how to get the Bitmap from any UI View and Save it to Storage/Gallery. For Example, we have a LinearLayout containing some child views such as ImageView(s), TextView(s), and maybe some more UI Views. On clicking a button we will save that LinearLayout as an image in storage/gallery. So by learning this technique you can save any UI View or Layout as an image in Storage/Gallery.

Photo by Sven Mieke on Unsplash

Let's Start making the XML layout of our Activity class. The LinearLayout with id infoLl is the Layout/View whose Bitmap will be saved as an Image in Storage/Gallery. The MaterialButton saveBtn will be clicked to get and save the Bitmap.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:padding="10dp"
tools:context=".MainActivity">

<TextView
android:id="@+id/titleTv"
style="@style/TextAppearance.MaterialComponents.Body1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Bitmap From Any View/Layout"
android:textAlignment="center" />

<LinearLayout
android:id="@+id/infoLl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical"
android:padding="10dp">

<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_gravity="center_horizontal"
android:src="@mipmap/ic_launcher" />

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Company: Technify Soft" />

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:autoLink="all"
android:text="Website: https://technifysoft.com" />


<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:autoLink="all"
android:text="YouTube: youtube.com/@AtifSayings" />

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:autoLink="all"
android:text="LinkedInn: linkedin.com/in/AtifSayings" />

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:autoLink="all"
android:text="Facebook: facebook.com/AtifSayings" />

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:autoLink="all"
android:text="Twitter: twitter.com/AtifSayings" />

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:autoLink="all"
android:text="Instagram: instagram.com/AtifSayings" />

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:autoLink="all"
android:text="Github: github.com/AtifSayings" />

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:autoLink="all"
android:text="Stack Overflow: stackoverflow.com/users/7981077/atifsayings" />

</LinearLayout>

<com.google.android.material.button.MaterialButton
android:id="@+id/saveBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:minHeight="60dp"
android:text="Save"
app:cornerRadius="8dp" />

</RelativeLayout>

Our Activity UI will look like this as in the Screenshot:

Let's Start coding in the Activity class.

package com.technifysoft.btimapfromlayout;

import android.content.ContentValues;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.button.MaterialButton;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {

private LinearLayout infoLl;
private MaterialButton saveBtn;
private static final String TAG = "SAVE_BITMAP";

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

//init UI Views
infoLl = findViewById(R.id.infoLl);
saveBtn = findViewById(R.id.saveBtn);

//handle saveBtn click
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//function call, to get Bitmap from a UI View i.e. In our case a LinearLayout with id infoLl
Bitmap bitmap = getBitmapFromUiView(infoLl);
//function call, pass the bitmap to save it
saveBitmapImage(bitmap);
}
});
}

/**Get Bitmap from any UI View
* @param view any UI view to get Bitmap of
* @return returnedBitmap the bitmap of the required UI View */
private Bitmap getBitmapFromUiView(View view) {
//Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
//Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
//Get the view's background
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null) {
//has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
} else {
//does not have background drawable, then draw white background on the canvas
canvas.drawColor(Color.WHITE);
}
// draw the view on the canvas
view.draw(canvas);

//return the bitmap
return returnedBitmap;
}

/**Save Bitmap To Gallery
* @param bitmap The bitmap to be saved in Storage/Gallery*/
private void saveBitmapImage(Bitmap bitmap) {
long timestamp = System.currentTimeMillis();

//Tell the media scanner about the new file so that it is immediately available to the user.
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
values.put(MediaStore.Images.Media.DATE_ADDED, timestamp);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values.put(MediaStore.Images.Media.DATE_TAKEN, timestamp);
values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/" + getString(R.string.app_name));
values.put(MediaStore.Images.Media.IS_PENDING, true);
Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (uri != null) {
try {
OutputStream outputStream = getContentResolver().openOutputStream(uri);
if (outputStream != null) {
try {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.close();
} catch (Exception e) {
Log.e(TAG, "saveToGallery: ", e);
}
}
values.put(MediaStore.Images.Media.IS_PENDING, false);
getContentResolver().update(uri, values, null, null);

Toast.makeText(this, "Saved...", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e(TAG, "saveToGallery: ", e);
}
}
} else {
File imageFileFolder = new File(Environment.getExternalStorageDirectory().toString() + '/' + getString(R.string.app_name));
if (!imageFileFolder.exists()) {
imageFileFolder.mkdirs();
}
String mImageName = "" + timestamp + ".png";

File imageFile = new File(imageFileFolder, mImageName);
try {
OutputStream outputStream = new FileOutputStream(imageFile);
try {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.close();
} catch (Exception e) {
Log.e(TAG, "saveToGallery: ", e);
}
values.put(MediaStore.Images.Media.DATA, imageFile.getAbsolutePath());
getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

Toast.makeText(this, "Saved...", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e(TAG, "saveToGallery: ", e);
}
}
}

}

Our code is completed, now you can launch the app and press the button to save. You will be able to see the Image in your Gallery in the album name the same as your app name.

Get & Save Bitmap From Any UI | Android Studio | Kotlin

Thank You for reading the article. If you found this article helpful make sure to click 👏 below to applause this article. It means a lot to me.

--

--

Atif Pervaiz

I'm Android & iOS Application developer & graphics Designer. Learning & delivering knowledge by making it easier to understand for others is my hobby & passion.