How to convert layout into image in android studio

Introduction: Some time we need to create image using layout so in this article i can give you code which is very helpful to you.


  1. Add Write external permission in manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2. Add condition to check either folder create or not

File file = saveBitMap(MainActivity.this, relativeLayout);
if (file != null) {

    Snackbar.make(relativeLayout, "Image Saved in DCIM Folder", Snackbar.LENGTH_LONG).show();
} else {

    Snackbar.make(relativeLayout, "Image not saved", Snackbar.LENGTH_LONG).show();

3. Add few function which are used for to converting layout int image

private File saveBitMap(Context context, View drawView) {
    File pictureFileDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "FolderName");
    if (!pictureFileDir.exists()) {
        boolean isDirectoryCreated = pictureFileDir.mkdirs();
        if (!isDirectoryCreated)
            Log.i("TAG", "Can't create directory to save the image");
        return null;
    String filename = pictureFileDir.getPath() + File.separator + System.currentTimeMillis() + ".jpg";
    File pictureFile = new File(filename);
    Bitmap bitmap = getBitmapFromView(drawView);
    try {
        FileOutputStream oStream = new FileOutputStream(pictureFile);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, oStream);
    } catch (IOException e) {
        Log.i("TAG", "There was an issue saving the image.");
    scanGallery(context, pictureFile.getAbsolutePath());
    return pictureFile;

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) {
    } else {
    return returnedBitmap;

private void scanGallery(Context cntx, String path) {
    try {
        MediaScannerConnection.scanFile(cntx, new String[]{path}, null, new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
    } catch (Exception e) {
        Log.i("TAG", "There was an issue scanning gallery.");

4. Now our code is complete. Allow app permission manually.

5. Run your app. Enjoy!!

Leave a Reply

Your email address will not be published. Required fields are marked *