1

I'm trying to convert a Linear layout into a bitmap. But it gives a null pointer exception. My code is.

The bitmap is null. As I am not getting the toast "not null". Why am i getting the bitmap as null. I have tried many similar questions but the code there is same.

public class Receipt extends Activity {

    public Bitmap bitmap;
    LinearLayout layout;
    private String fileName;
    private File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.receipt);
        ImageView iv = (ImageView) findViewById(R.id.Ivsignature);
        iv.setImageBitmap(Signature.sign);

        layout = (LinearLayout) findViewById(R.id.Llreceipt);
        layout.setDrawingCacheEnabled(true);
        layout.buildDrawingCache();
        bitmap = layout.getDrawingCache(true);

        if (bitmap != null)
            Toast.makeText(getApplicationContext(), "not null",
                    Toast.LENGTH_LONG).show();
        String myPath = Environment.getExternalStorageDirectory()
                + "/signature_image";
        File myDir = new File(myPath);
        try {
            myDir.mkdirs();
        } catch (Exception e) {
        }

        String fname = fileName + "gwg" + ".jpg";
        file = new File(myDir, fname);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bitmap.compress(CompressFormat.JPEG, 100, fos);
            Toast.makeText(getApplicationContext(), "File saved",
                    Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), String.valueOf(e),
                    Toast.LENGTH_LONG).show();
        }
    }
}

3 Answers 3

4

You can draw your view to a canvas instantiated with a bitmap, so the view will be written to the bitmap. After drawing to that canvas the bitmap will contain the view.

Make sure to call the function below after your view has been laid out and actually has a width and height

public Bitmap createBitmapForView(View view)
{
    int width = view.getWidth();
    int height = view.getHeight();

    // create a bitmap the size of the view
    Bitmap screenShot = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

    // create a canvas with the bitmap
    Canvas canvas = new Canvas(screenShot);

    // draw the view to the canvas
    view.draw(canvas);

    // now your bitmap contains the view
    return screenShot;
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can't do this in onCreate as the view has not yet been drawn. You could use a ViewTreeObserver or override onAttachedToWindow() in your activity.

http://developer.android.com/reference/android/view/ViewTreeObserver.html

Comments

0
package com.example.snapshotlayout;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.View.MeasureSpec;
import android.widget.ImageView;
import android.widget.TextView;

public class SnapshotActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_snapshot);

    //initializing layouts
    TextView textView = (TextView)findViewById(R.id.textView);
    ImageView snapImage = (ImageView)findViewById(R.id.imageView);
    textView.setDrawingCacheEnabled(true);

    //specifying the dimensions of view
    textView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
          MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

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

    textView.buildDrawingCache(true);
    Bitmap b = Bitmap.createBitmap(textView.getDrawingCache());
    textView.setDrawingCacheEnabled(false); // clear drawing cache

    snapImage.setImageBitmap(b);   

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

    //create a new file in sdcard name it as "testimage.jpg"
    File fileImage = new File(Environment.getExternalStorageDirectory()
                            + File.separator + "testimage.jpg");

    //write the bytes in file
    FileOutputStream fo = null;
    try {
        fileImage.createNewFile();
        fo = new FileOutputStream(fileImage);
        fo.write(bytes.toByteArray());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

here is the code for xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:id="@+id/snapLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
<TextView
    android:id="@+id/textView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Take snapshot of this layout"/>
<ImageButton  
    android:id="@+id/imageView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

</LinearLayout>

taken from http://hoodaandroid.blogspot.in/2012/09/taking-snapshot-or-screen-capture-of.html

2 Comments

This won't work with hardware acceleration on since the drawingCache is not used then
Very true, just wanted to add that in case anyone who reads this encounters such problems

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.