Share loaded image with glide from imageview - android

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);
}

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;
}
}

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());
}
});

current activity screen shot and share it with share icon in action bar

I want to take current activity screenshot and share it on share item click in actionbar share button. When I run application nothing would be shown me as a output. How can I take current screen screenshot? please tell me the proper sequence of it.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item:
try{
takeScreenShot(av); // av is instance of hello
}
catch (Exception e) {
System.out.println(e);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public static void shoot(Activity a,String b) {
//savePic(takeScreenShot(a), "sdcard/xx.png");
savePic(takeScreenShot(a), b);
}
private 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;
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay().getHeight();
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
return b;
}
private static void savePic(Bitmap b, String strFileName)
{
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(strFileName);
if (null != fos)
{
b.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
fos.close();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Here is the code that allowed my screenshot to be stored on sd card and used later for whatever your needs are:
First, add proper permission to save file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the code (running in an Activity):
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
And this is how you can open the recently generated image:
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
check this answer https://stackoverflow.com/a/5651242/4342876

How to save an image attached to the image view?

I am using a Glide library for loading remote URLs into ImageView's.
I want to save the image from this ImageView to gallery. (I don't want to make another network call again to download the same image).
How we can achieve this?
Glide.with(yourApplicationContext))
.load(youUrl)
.asBitmap()
.into(new SimpleTarget<Bitmap>(myWidth, myHeight) {
#Override
public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
//set bitmap to imageview and save
}
};
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, false);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 60, byteArrayOutputStream);
String fileName = "image.jpeg";
File file = new File("your_directory_path/"
+ fileName);
try {
file.createNewFile();
// write the bytes in file
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(byteArrayOutputStream.toByteArray());
// remember close the FileOutput stream
fileOutputStream.close();
ToastHelper.show(getString(R.string.qr_code_save));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ToastHelper.show("Error");
}
Note : If your drawble is not always an instanceof BitmapDrawable
Bitmap bitmap;
if (mImageView.getDrawable() instanceof BitmapDrawable) {
bitmap = ((BitmapDrawable) mImageView.getDrawable()).getBitmap();
} else {
Drawable d = mImageView.getDrawable();
bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Try this
I haven't try this way. But i think this match your problem. Put this code on onBindViewHolder of your RecyclerView adapter.
Glide.with(yourApplicationContext))
.load(youUrl)
.asBitmap()
.into(new SimpleTarget<Bitmap>(myWidth, myHeight) {
#Override
public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
//Set bitmap to your ImageView
imageView.setImageBitmap(bitmap);
viewHolder.saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//Save bitmap to gallery
saveToGallery(bitmap);
}
});
}
};
This might help you
public void saveBitmap(ImageView imageView) {
Bitmap bitmap = ((GlideBitmapDrawable) imageView.getDrawable()).getBitmap();
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/My Images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception ex) {
//ignore
}
}

Android - Not taking screenshot of current screen

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"));
}

Categories

Resources