RelativeLayout screenshot including mapFragment saves black image - java

I have a RelativeLayout view which includes some TextViews and a map fragment. I want to take a screenshot of the whole screen (including the map as displayed and the text) and save it. Everything working as expected but the view with the map shows a black image. How is this possible?
I've also tried with some delay interval to be sure the map is fully loaded but didn't worked.
Bitmap bitmap = takeScreenshot();
createDirectoryAndSaveFile(bitmap,intent.getStringExtra("TEST"));
public Bitmap takeScreenshot() {
View rootView = findViewById(R.id.relative_layout);
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
private void createDirectoryAndSaveFile(Bitmap bitmap, String name) {
File folder = new File(Environment.getExternalStorageDirectory() +"/Test");
if (!folder.exists()) {
File screenshoDir = new File(Environment.getExternalStorageDirectory() + "/Test/");
screenshoDir.mkdirs();
}
File file = new File(new File(Environment.getExternalStorageDirectory() + "/Test/"), name);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
MediaScannerConnection.scanFile(this, new String[]{file.getPath()}, new String[]{"image/jpeg"}, null);
} catch (Exception e) {
e.printStackTrace();
}
}

Related

Saving Image from an Image-View to device

I have two Image-View in a layout, one as at background and another is above that(at foreground) and I want to save both the images. So can anyone help me out that how can I save both the images into the device storage as single image.
Thank you.
A simple solution I found here is to put both of your imageView in a single Layout and then save your layout as a Bitmap. I will retype the solution code here
private Bitmap getBitmap(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
// Reset the drawing cache background color to fully transparent
// for the duration of this operation
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
Toast.makeText(StopWarApp.getContext(), "Something went wrong",
Toast.LENGTH_SHORT).show();
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
// Restore the view
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
Now that you have your Bitmap, you can save it to your storage like this
private void saveImage(Bitmap finalBitmap, String image_name) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root);
myDir.mkdirs();
String fname = "Image-" + image_name+ ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Don't forget to add your permissions in the manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How to send image from app via messenger?

I want to send image from my app via messenger. I was looking on Stack Overflow and I found answer which works for WhatsApp. When I tried to change "com.whatsapp" to "com.facebook.orca", it stops working. Here is my code:
public void shareImageMessenger() {
Bitmap adv = BitmapFactory.decodeResource(getResources(), R.drawable.koza);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
adv.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "temporary_file_1.jpg");
try {
f.createNewFile();
new FileOutputStream(f).write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM,
Uri.parse( Environment.getExternalStorageDirectory()+ File.separator+"temporary_file_1.jpg"));
share.setPackage("com.facebook.orca");
startActivity(Intent.createChooser(share, "Share Image"));
}
After spending a lot of time on this:
Check if permissions are given. Then:
Step 1: Create ImageView of the image you want to in the activity and then convert it itno bitmap
ImageView imageView = findViewById(R.id.image);
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
//save the image now:
saveImage(bitmap);
//share it
send();
Step 2: Store the image in internal folder:
private static void saveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
Log.i("Directory", "==" + myDir);
myDir.mkdirs();
String fname = "Image-test" + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Step 3: Send the saved image:
public void send() {
try {
File myFile = new File("/storage/emulated/0/saved_images/Image-test.jpg");
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
String type = mime.getMimeTypeFromExtension(ext);
Intent sharingIntent = new Intent("android.intent.action.SEND");
sharingIntent.setType(type);
sharingIntent.putExtra("android.intent.extra.STREAM", Uri.fromFile(myFile));
startActivity(Intent.createChooser(sharingIntent, "Share using"));
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
Now after sending you can delete the saved image if you don't want it in your storage. Check other link to do that.
Referring your linked post,You could modify the share intent.
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///assets/epic/adv.png"));
this.startActivity(Intent.createChooser(share, "share_via"));
The intent launches the apps which handles Intent.ACTION_SEND. If you want specific app to be respond, make sure you are aware of the package name and you need set package name share.setPackage("");

Share screen shoot android studio(multi-times)

I have app and i am letting user to make screenshot and share it, all working fine just one problem..
When user for example make screenshot and press on Facebook icon > then he press cancel sharing ,next time when he want to do another share he will see the old screen shoot , how can make it take the last screenshot always??
** i have each image has different file name but the share always taking the last action that didn't finish.
(if user do share all will work fine ,next screen shoot will be the new one )
here is my code
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
imagePath = new File(Environment.getExternalStorageDirectory() ,
"SCREEN"
+ System.currentTimeMillis() + ".png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
private void shareIt() {
uri =Uri.fromFile(imagePath);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("image/*");
String shareBody = "جرب تطبيق نكت عراقية مضحكة الان!";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "تطبيق نكت
عراقية مضحكة");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sharingIntent, "مشاركة بواسطة"));
}
You can do something like this.Remove the System.currentTimeMillis() from the name of your image so, that you do not have multiple copies of screenshots.So when you upload the image it always have the fresh screenshots.Now when you capture another screenshot you have to check is file exist if exist then delete it.
public void saveBitmap(Bitmap bitmap)
{
File file = new File(Environment.getExternalStorageDirectory(), "SCREEN.png");
if (file.exists()) {
file.delete();
}
imagePath = new File(Environment.getExternalStorageDirectory() , "SCREEN.png");
FileOutputStream fos;
try
{
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}
catch (IOException e)
{
Log.e("GREC", e.getMessage(), e);
}
}

Android saving images in application context

In my MainActivity onCreate() I want to populate a listview. This listview contains Strings and Bitmaps.
What's the best way to save these data to get them back when the application is restarted ?
There is my own cache solution:
public class MyCache {
private String DiretoryName;
public void OpenOrCreateCache(Context _context, String _directoryName){
File file = new File(_context.getCacheDir().getAbsolutePath() + "/" + _directoryName);
if(!file.exists()){
file.mkdir();
}
DiretoryName = file.getAbsolutePath();
}
public void SaveBitmap(String fileName, Bitmap bmp){
try {
File file = new File(DiretoryName+ "/" + fileName);
if(file.exists()){
file.delete();
}
FileOutputStream Filestream = new FileOutputStream(DiretoryName + "/" + fileName);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
Filestream.write(byteArray);
Filestream.close();
bmp.recycle();
}
catch (Exception e){
e.printStackTrace();
}
}
public Bitmap OpenBitmap(String name){
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
File file = new File(DiretoryName+ "/" + name);
if(file.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(DiretoryName+ "/" + name, options);
return bitmap;
}
else{
return null;
}
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
public void CleanCacheBitMap(){
File file = new File(Diretorio);
if(file.exists()){
file.delete();
}
}
}
And onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
cache = new MyCache();
cache.OpenOrCreateCache(this, "TheFolderNameForOpenOrSaveInAppCache");
}
And for save on runtime:
cache.SaveBitmap("BitMapName", YourBitmap);
And openning on runtime:
Bitmap bmp = cache.OpenBitmap("BitMapName");
This solution save any bitmap, in particular folder in your app cache (internal storage).
There are different possibilities depending on how tightly you want to hang on to these files. The most reliable is the method getFilesDir(). Each application has its own private "files directory".
All the details are here:
https://developer.android.com/training/basics/data-storage/files.html
The cache directory (getCacheDir()) is similar but the user can erase the cache contents so that's more for temporary files you don't want to hang onto.
Strings and bitmaps can both be saved to files. You can create your own name value mapping file to link them. Or use JSON objects, or many other things to organize your list of strings/bitmaps.

Android App saving to SD Card

I'm having some trouble. I'm new to java and Android programming. I'm using a template to get started and I'm stuck.
I have a app that pulls images from my Tumblr Feed and presents them on the screen with a download button. It works fine but installs to the root of the internal storage. How do I save it to a folder in the internal storage called "/Pictures/Tumblr"?
My code is:
public void onLoadingComplete(final String imageUri, View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
// close button click event
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "tumblr_"+images.get(position).getId()+".jpg");
try {
fOut = new FileOutputStream(file);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
String saved = getResources().getString(R.string.saved);
Toast.makeText(getBaseContext(), saved + " " + file.toString(), Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
I've tried changing the
File file = new File(path, "tumblr_"+images.get(position).getId()+".jpg");
To
File file = new File(path+"/Pictures/Tumblr", "tumblr_"+images.get(position).getId()+".jpg");
But I know it's wrong.
Can anyone help?

Categories