Skip to content

Instantly share code, notes, and snippets.

@antocara
Last active September 16, 2023 06:22
Show Gist options
  • Save antocara/5fb2904df2c7de34ebe9 to your computer and use it in GitHub Desktop.
Save antocara/5fb2904df2c7de34ebe9 to your computer and use it in GitHub Desktop.
Convert View to Bitmap Android
private void savedBitmapFromViewToFile(){
//inflate layout
View layout = LayoutInflater.from(this).inflate(R.layout.activity_main, null, false);
RelativeLayout mContImage = (RelativeLayout) layout.findViewById(R.id.image_cont);
//reference View with image
mContImage.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
Bitmap bitmap = Bitmap.createBitmap(mContImage.getMeasuredWidth(), mContImage.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
mContImage.layout(0, 0, mContImage.getMeasuredWidth(), mContImage.getMeasuredHeight());
mContImage.draw(canvas);
//save to File
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String nameFile = "imageFromView.jpg";
File f = new File(Environment.getExternalStorageDirectory() + File.separator + nameFile);
FileOutputStream fo = null;
try {
fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
} catch (Exception e) {
Log.d("Error File:" , "" + e);
}
}
@souhaib100
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment