Skip to content

Instantly share code, notes, and snippets.

@Asutosh11
Last active November 29, 2016 08:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Asutosh11/8cc817932173f8d28d6e409a4a4a7fe5 to your computer and use it in GitHub Desktop.
Save Asutosh11/8cc817932173f8d28d6e409a4a4a7fe5 to your computer and use it in GitHub Desktop.
Android Java Class to take a snapshot of a View on screen and save as Image
/*
This class converts any Layout or View to image and saves in Phone.
In one of my projects, I had a requirement of saving whatever is being displayed on the Screen as an image.
I created a class for it so that in future it becomes easy to reuse.
Usage Example
-----------------------------------------------------------------------------------------------------------
FrameLayout mLin_FramePreview1 = (FrameLayout)findViewById(R.id.lin_FramePreview1);
ViewToImage v = new ViewToImage(mLin_FramePreview1);
*/
 public class ViewToImage {
// This Class is tested by passing a FrameLayout, LinearLayout, RelativeLayout here
/*
This Constructor accepts a View as a parameter.
You can pass the top level parent View to capture the whole screen.
To know how to use it, see 'Usage Example' above.
*/
public ViewToImage(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
try {
// I'm storing the output image in this path. Change the path and image name if you want
FileOutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/savedImage.png");
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment