Android - Not taking screenshot of current screen - android

Code work fine for first screenshot and keep taking same screenshot regardless of moving to another view.
How to get current screenshot?
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/" + new SimpleDateFormat("yyyyMMddhhmmss'.jpg'").format(new Date()) );
FileOutputStream fos =null;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
click info:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iSave:
Bitmap bitmap = null;
bitmap = takeScreenshot();
saveBitmap(bitmap);
break;
}
}
here:
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}

Call rootView.setDrawingCacheEnabled(false); after taking the screen-shot. Turning it off and then on again forces it to update correctly.
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
Bitmap bitmap = rootView.getDrawingCache();
rootView.setDrawingCacheEnabled(false);
return bitmap;
}

I have ever tried to capture the current Activity and then share the screenshot. This below is how I did, take a look at them if you are still interested, and I think you would agree.
First, the get the root view of current Activity:
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
or
View rootView = findViewById(android.R.id.content);
or
View rootView = findViewById(android.R.id.content).getRootView();
Second, get Bitmap from the root view:
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
Third, store the Bitmap into the SDCard:
private final static String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
public static void store(Bitmap bm, String fileName){
File dir = new File(dir);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
At last, share the screenshot file:
private void shareImage(String file){
Uri uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share Screenshot"));
}

Related

Facing issue to taking snapshot for particular view

When I am taking snapshot of particular view in android. My whole view going to be blank after taking the screenshot. please check my whole code where I did wrong. I have searched so many quotes in Google but not able to solve my problem. Please someone help me.
// here is my code
fb_share_btn.setOnClickListener (new View.OnClickListener ( ) {
#Override
public void onClick(View view) {
boolean checkPermission = checkPermission();
/*Bitmap bitmap = takeScreenshot();*/
Bitmap bitmap = loadBitMapFromView(findViewById (R.id.tv_screenshot),findViewById (R.id.tv_screenshot).getWidth (),findViewById (R.id.tv_screenshot).getHeight ());
saveBitmap(bitmap);
shareIt();
}
});
// save bitmap function
public void saveBitmap(Bitmap bitmap) {
imagePath = new File (Environment.getExternalStorageDirectory ()+ "/screenshot.png");
Log.i ("Message","Testingabc:"+ imagePath);
FileOutputStream fos;
try {
fos = new FileOutputStream (imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
private Bitmap loadBitMapFromView(View v, int width, int height) {
Bitmap b = Bitmap.createBitmap(width , height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas (b);
c.drawColor (Color.WHITE);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
return b;
}
private void shareIt() {
Uri uri = FileProvider.getUriForFile(TimeCounter.this, BuildConfig.APPLICATION_ID + ".provider",imagePath);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/*");
String shareBody = "In Tweecher, My highest score with screen shot";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Tweecher score");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
sharingIntent.setPackage("com.facebook.katana");
startActivity(sharingIntent);
}
}
use this code with AsycTask
#Override
protected void onPreExecute() {
try {
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected Integer doInBackground(Integer... integers) {
try {
File root = new File(Environment.getExternalStorageDirectory(), "/Screenshot/");
if (!root.exists()) {
root.mkdirs();
}
imageFile = new File(root.toString() + "/" + imageName + ".jpg");
FileOutputStream outputStream = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 75, outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}

Share loaded image with glide from imageview

I have a loaded image on my imageview widget which was loaded from glide library. I want to use a share intent to share that image to other applications. I have tried various possibilities without any success. Please help.
public class BookstorePreviewActivity extends AppCompatActivity {
ImageView imageView;
LinearLayout mShare;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookstore_preview);
imageView = findViewById(R.id.image_preview_books);
mShare= findViewById(R.id.download_books);
mShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// fetching image view item from cache
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
File root = Environment.getExternalStorageDirectory();
File cachePath = new File(root.getAbsolutePath());
try {
cachePath.createNewFile();
FileOutputStream outputStream = new FileOutputStream(cachePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// sharing image to other applications (image not found)
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(cachePath));
startActivity(Intent.createChooser(share, "Share via"));
}
});
Just Pass activity context to the takeScreenShot activity it will
work!!!
public static Bitmap takeScreenShot(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
//Find the screen dimensions to create bitmap in the same size.
DisplayMetrics dm = activity.getResources().getDisplayMetrics();
int width = dm.widthPixels;
int height = dm.heightPixels;
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
takeScreen(b,activity);
return b;
}
public static void takeScreen(Bitmap bitmap,Activity a) {
//Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
String mPath = Environment.getExternalStorageDirectory() + File.separator + "tarunkonda" + System.currentTimeMillis() + ".jpeg";
File imageFile = new File(mPath);
try {
OutputStream fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
openScreenshot(imageFile,a);
}
private static void openScreenshot(File imageFile,Activity activity) {
Intent intent = new Intent(activity,ImageDrawActivity.class);
intent.putExtra(ScreenShotActivity.PATH_INTENT_KEY,imageFile.getAbsolutePath());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}

How do I take screenshot or save as image my fragment app in android studio

I have recently made an app memegenerator
screenshot : enter image description here
I want whenever I click on the button to create meme
it should automatically save that picture below (which is a fragment)
How do I do that I have no idea?
This is what I found on internet to place in my code
Should I add this on my mainactivity file or the fragment java file
` public void createBitmap()
{
//Log.d(Const.DEBUG,"Creating a Bitmap");
Bitmap bmp;
ViewGroup v = (ViewGroup)((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
v.setDrawingCacheEnabled(true);
bmp = Bitmap.createBitmap(v.getDrawingCache());
File directory = new File(Environment.getExternalStorageDirectory()+ File.separator);
File file = new File(directory,"DankMeme");
try{
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG,100,out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
v.destroyDrawingCache();
v.setDrawingCacheEnabled(false);
}`
**update This my fragment code **
public class BottomSectionFragment extends Fragment {
private static TextView topMemeText;
private static TextView bottomMemeText;
private View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.bottom_picture_fragment,container,false);
topMemeText = (TextView)view.findViewById(R.id.topMemeText);
bottomMemeText = (TextView)view.findViewById(R.id.bottomMemeText);
return view;
}
public void setMemeText(String top,String bottom)
{
topMemeText.setText(top);
bottomMemeText.setText(bottom);
//createBitmap();
// I am calling tackeAndSaveScreenshot func here because when user press button it comes to this func
// to change text and right after I want screenshot
tackeAndSaveScreenShot();
}
//Screenshot
public void tackeAndSaveScreenShot() {
View MainView = getActivity().getWindow().getDecorView();
MainView.setDrawingCacheEnabled(true);
MainView.buildDrawingCache();
Bitmap MainBitmap = MainView.getDrawingCache();
Rect frame = new Rect();
getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
//to remove statusBar from the taken sc
int statusBarHeight = frame.top;
//using screen size to create bitmap
int width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
int height = getActivity().getWindowManager().getDefaultDisplay().getHeight();
Bitmap OutBitmap = Bitmap.createBitmap(MainBitmap, 0, statusBarHeight, width, height - statusBarHeight);
MainView.destroyDrawingCache();
try {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
//you can also using current time to generate name
String name="YourName";
File file = new File(path, name + ".png");
fOut = new FileOutputStream(file);
OutBitmap.compress(Bitmap.CompressFormat.PNG, 90, fOut);
fOut.flush();
fOut.close();
//this line will add the saved picture to gallery
MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This method will take screenshot from your mobile screen. you can change the MainView to your view that you want to take screenshot from.
Don't forget to add "Write external storage" permission to manifest
public void tackeAndSaveScreenShot(Activity mActivity) {
View MainView = mActivity.getWindow().getDecorView();
MainView.setDrawingCacheEnabled(true);
MainView.buildDrawingCache();
Bitmap MainBitmap = MainView.getDrawingCache();
Rect frame = new Rect();
mActivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
//to remove statusBar from the taken sc
int statusBarHeight = frame.top;
//using screen size to create bitmap
int width = mActivity.getWindowManager().getDefaultDisplay().getWidth();
int height = mActivity.getWindowManager().getDefaultDisplay().getHeight();
Bitmap OutBitmap = Bitmap.createBitmap(MainBitmap, 0, statusBarHeight, width, height - statusBarHeight);
MainView.destroyDrawingCache();
try {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
//you can also using current time to generate name
String name="YourName";
File file = new File(path, name + ".png");
fOut = new FileOutputStream(file);
OutBitmap.compress(Bitmap.CompressFormat.PNG, 90, fOut);
fOut.flush();
fOut.close();
//this line will add the saved picture to gallery
MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
calling method by using :
Button memeDanke = (Button) view.findViewById(R.id.memeDanke);
memeDanke.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tackeAndSaveScreenShot(getActivity());
}
});

I need to convert a bitmap to uri to send to use it in image cropper library in android?

Here i am making drawable view into bitmap.
mDrawingPad.setVisibility(View.VISIBLE);
BitmapDrawable ob = new BitmapDrawable(getResources(),
bitmapconv);
DrawingView mDrawingView=new
DrawingView(Previewimage.this);
mDrawingPad.addView(mDrawingView);
mDrawingView.setBackground(ob);
mDrawingView.buildDrawingCache();
drawbitmap=mDrawingView.getDrawingCache();
I need to convert this into URI to send to image cropper library
CropImage.activity(uri).start(Previewimage.this);
/*This saveImage method will return String path*/
path = saveImage();
Uri uri = Uri.parse(path);
/****************************************************/
private String saveImage()
{
Bitmap bitmap;
mDrawingView.setDrawingCacheEnabled(true);
mDrawingView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
mDrawingView.buildDrawingCache();
bitmap = Bitmap.createBitmap(mDrawingView.getDrawingCache());
String state = Environment.getExternalStorageState();
String root = "";
String fileName = "/MyImage" + System.currentTimeMillis() + "Image"+ ".jpg";
String parent = "App_Name";
File mFile;
if (Environment.MEDIA_MOUNTED.equals(state)) {
root = Environment.getExternalStorageDirectory().toString();
mFile = new File(root, parent);
if (!mFile.isDirectory())
mFile.mkdirs();
} else {
root = FriendsImageSending.this.getFilesDir().toString();
mFile = new File(root, parent);
if (!mFile.isDirectory())
mFile.mkdirs();
}
String strCaptured_FileName = root + "/App_Name" + fileName;
File f = new File(strCaptured_FileName);
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 95, bytes);
FileOutputStream fo;
fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
bitmap.recycle();
System.gc();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return strCaptured_FileName;
}
This part of code works:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
your_bitmap_image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(your_context.getContentResolver(), your_bitmap_image, "your_title", null);
Uri uri = Uri.parse(path);
just try to replace the areas that I mentioned in it
in the place of "your_context" if you are in an activity put this:
MediaStore.Images.Media.insertImage(getContentResolver(), your_bitmap_image, "your_title", null);
Uri uri = Uri.parse(path);
if you are in a fragment :
MediaStore.Images.Media.insertImage(getContext().getContentResolver(), your_bitmap_image, "your_title", null);
Uri uri = Uri.parse(path);
Use this method:
public Uri getImageUri(Context ctx, Bitmap bitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(ctx.getContentResolver(),
bitmap, "Temp", null);
return Uri.parse(path);
}
If you are calling this method inside an Activity then call this method like this:
getImageUri(YourClassName.this, yourbitmap);
But if you are calling this in an Fragment then call like this:
getImageUri(getActivity(), yourbitmap);

Saving an image to sd card from android pager

I have a pager activity in my android application I need to save the images according to there position in the pager. I managed to do the saving part but when iam in the first image i click save it saves the second image same for the second image it save the third i dont know whats wrong with my code! `
enter code here
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
if (item.getItemId()==R.id.menuFinale)
{
ImageView imageView = (ImageView) findViewById(R.id.image_one);
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
File root = Environment.getExternalStorageDirectory();
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "My pic" ,"Saved to gallery");
File file = new File(root.getAbsolutePath()+"/DCIM/Camera/img.jpg");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 100, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return true;
}
else {
return super.onOptionsItemSelected(item);
}
}
Try some thing as below :
button=(Button)vi.findViewById(R.id.button_save);
button.setOnClickListener(new OnClickListener() {
private Bitmap bm;
private String PREFS_NAME;
public void onClick(View arg0) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
if(!myDir.exists()){
myDir.mkdirs();}
bm = BitmapFactory.decodeResource( mContext.getResources(), images[itemPos]);
holder.image.setImageBitmap(bm);
SharedPreferences savedNumber = mContext.getSharedPreferences(PREFS_NAME, 0);
int lastSavedNumber = savedNumber.getInt("lastsavednumber",0);
lastSavedNumber++;
String fname = "Image-"+lastSavedNumber+".png";
File file = new File (myDir, fname);
if (file.exists ()) {file.delete (); }
try {
FileOutputStream out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, out);//Your Bitmap from the resouce
out.flush();
out.close(); }
catch (Exception e) {
e.printStackTrace();
}
SharedPreferences saveNumber = mContext.getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editorset = saveNumber.edit();
editorset.putInt("lastsavednumber",lastSavedNumber);
editorset.commit();
Toast.makeText(mContext, "saved", Toast.LENGTH_SHORT). show();}});
hope help you.
I managed finally to solve my issue instead of the imageView I'm referring to cache I must instead refer to ViewPager to cache all including the imageView instead here is my new code
enter code here
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
if (item.getItemId()==R.id.menuFinale)
{
pager.setDrawingCacheEnabled(true);
pager.buildDrawingCache(true);
pager.setDrawingCacheEnabled(true);
Bitmap b = pager.getDrawingCache(true);
File root = Environment.getExternalStorageDirectory();
MediaStore.Images.Media.insertImage(getContentResolver(), b, "My pic" ,"Saved to gallery");
File file = new File(root.getAbsolutePath()+"/DCIM/HD.jpg");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
b.compress(CompressFormat.JPEG, 100, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return true;
}
else
{
return super.onOptionsItemSelected(item);
}
}

Categories

Resources