How to convert a LinearLayout to image?

How to convert a LinearLayout to image?



I tried the following code to convert the LinearLayout to image:


LinearLayout


public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

LinearLayout lyt = (LinearLayout) findViewById(R.id.lyt);
lyt.setDrawingCacheEnabled(true);
lyt.buildDrawingCache(true);

Bitmap b = Bitmap.createBitmap(lyt.getDrawingCache());

ImageView img = (ImageView) findViewById(R.id.imageView1);
img.setImageBitmap(b);




but I got NullPointerException in :


NullPointerException


Bitmap b = Bitmap.createBitmap(lyt.getDrawingCache());



where the layout XML is :


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >


<LinearLayout
android:id="@+id/lyt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1" />

<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 3" />

</LinearLayout>

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />

</LinearLayout>




5 Answers
5


**Try below code, it works**

**Add below permission in manifest**

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
**MainActivity.java**

public class MainActivity extends Activity implements OnClickListener{
private LinearLayout linearLayout;
private Button saveBtn;

@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
linearLayout = (LinearLayout) findViewById(R.id.linearLayout_view);
saveBtn = (Button) findViewById(R.id.save_btn);
saveBtn.setOnClickListener(this);


@Override
public void onClick(View v)
int id = v.getId();
switch (id)
case R.id.save_btn:
File file = saveBitMap(this, linearLayout); //which view you want to pass that view as parameter
if (file != null)
Log.i("TAG", "Drawing saved to the gallery!");
else
Log.i("TAG", "Oops! Image could not be saved.");

break;
default:
break;


private File saveBitMap(Context context, View drawView)
File pictureFileDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"Handcare");
if (!pictureFileDir.exists())
boolean isDirectoryCreated = pictureFileDir.mkdirs();
if(!isDirectoryCreated)
Log.i("ATG", "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
pictureFile.createNewFile();
FileOutputStream oStream = new FileOutputStream(pictureFile);
bitmap.compress(CompressFormat.PNG, 100, oStream);
oStream.flush();
oStream.close();
catch (IOException e)
e.printStackTrace();
Log.i("TAG", "There was an issue saving the image.");

scanGallery( context,pictureFile.getAbsolutePath());
return pictureFile;

//create bitmap from view and returns it
private Bitmap getBitmapFromView(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;

// used for scanning gallery
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)
e.printStackTrace();







thanks :) your answer shows me an important hint to set background, which works like charm.
– Alok Vishwakarma
Sep 22 '16 at 15:17



My guess is that you are executing that code in onCreate. The problem with that is that the views are not layouted yet. Either call lyt.measure or call the code later. e.g: to onSizeChanged() or in onLayout() after you called super.onLayout().





how to call lyt.onMeasure() ??!
– Adham
Apr 29 '12 at 18:40





sorry the function is measure(). But i recommend to create the bitmap later and not call measure().
– Renard
Apr 29 '12 at 18:42


Bitmap b = Bitmap.createBitmap(lyt.getDrawingCache());



the only thing that can be null in that line is lyt, the rest can't. You probably did not set the layout yet and findViewById() will return null in that case.


null


lyt


findViewById()


null



You have to do setContentView() before you can do findViewById()


setContentView()


findViewById()





No I have already done that
– Adham
Apr 29 '12 at 18:13





Hmm that should mean the error does not happen on that line but somewhere inside Bitmap.createBitmap() or lyt.getDrawingCache(). And I guess Renard is right, if the views did not layout themselves they don't know how to draw themselves.
– zapl
Apr 29 '12 at 18:17


Bitmap.createBitmap()


lyt.getDrawingCache()





got inverted image.
– KIRAN K J
Apr 10 '13 at 12:22



See if that helps you:



Converting Views to Bitmap Images in Android



Below is the code snipet which converts xml layouts to Bitmap images


private Bitmap convertLayoutToImage()
LinearLayout linearView = (LinearLayout) this.getLayoutInflater(null).inflate(R.layout
.marker_layout, null, false); //you can pass your xml layout

linearView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
linearView.layout(0, 0, linearView.getMeasuredWidth(), linearView.getMeasuredHeight());

linearView.setDrawingCacheEnabled(true);
linearView.buildDrawingCache();
return linearView.getDrawingCache();// creates bitmap and returns the same






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ