Problems on sharing bitmap images - android

I have used com.nostra13.universalimageloader to load image. Inside the standard ImageAdapter in a ViewPager, there is a share button to share the bitmap. The code is as follows:
Code:
#Override
public Object instantiateItem(ViewGroup view, int position)
{
....
#Override
public void onLoadingComplete(String imageUri, View view, final Bitmap loadedImage)
{
spinner.setVisibility(View.GONE);
btn_share = (ImageButton) imageLayout.findViewById(R.id.btn_share);
btn_share.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Shining Card";
File dir = new File(file_path);
if (!dir.exists()) dir.mkdirs();
File file = new File(dir, "to share");
FileOutputStream fOut;
try
{
fOut = new FileOutputStream(file);
loadedImage.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
}
catch (Exception e)
{
e.printStackTrace();
Constants.custom_toast(getActivity(), "Error when sharing", "");
}
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 Cover Image"));
}
});
}
Question:
The problem lies on sharing the image.
Share via whatsapp
Sharing the first image via whatsapp, the image can be shared successfully to others. Continues with sharing second image it also works successfully.
However, if the sharing of the first image is cancelled in whatsapp and return to the app, and then choose another image to share in whatsapp, the preview in whatsapp will remain as the first image, though if ignore it and continue to share whatsapp will actually share the new image. (i.e. there is a preview problem) (using other app to share image perform the same, preview in whatsapp does not go wrong)
Share via gmail
Sharing the image as attachment via gmail, the image cannot be previewed nor opened.

Related

Android how to Share GIF image to all Apps without converting it to in jpg or png format

Can any body tell me how can i share GIF image in android programmatically like.
Actually i want to share GIF image like android share .jpg or .png images.
I search a lot of but there is no link to share GIF image,please if anybody know please tell me.
code for sharing GIF image? startActivity(Intent.createChooser(shareIntent,"Share Emoji")); is used to share data using intent with the title "Share Emoji" whenever we share jpg or png it works perfectly. But if we try to send GIF images it does not work perfectly only email way works, if we select any other app to share GIF image like WhatsApp or Shareit, it converts GIF image to simple png image..... By this code only, i am unable to share GIF image with every other apps. So please check it and give me reasonable & practical solution if this is possible
Thank you
===============================================================
this is my code which i used currently
public class SplashScreen extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_main);
Button click = (Button) findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
shareGif(getResources().getResourceName(R.drawable.clark));
}
});
}
private void shareGif(String resourceName) {
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "sharingGif.gif";
File sharingGifFile = new File(baseDir, fileName);
try {
byte[] readData = new byte[1024 * 500];
InputStream fis = getResources().openRawResource(getResources().getIdentifier(resourceName, "drawable", getPackageName()));
FileOutputStream fos = new FileOutputStream(sharingGifFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
System.out.println("===sharing file=="+sharingGifFile);
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/gif");
Uri uri = Uri.fromFile(sharingGifFile);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share Emoji"));
}
}

Clear share intent data while whatsapp sharing in android

I have a Relative layout and Textview on it. Then I convert that relative layout to bitmap image and save in directory.
The problem is when I am sharing the image, in most of app, I found correct image but in case of whatsapp when I am sharing through whatsapp the preview of sharing image is showing me old one until I close the app. Why it's not getting update and when I share the image on whatsapp, preview is old one and the image goes right one. This works fine in FB, Gmail etc...
This is the below code for converting and saving converted bitmap image in file system (directory)
This is for creating Direcory:
File dir = null;
String directorySubPath = "Android/data/com.domainname.appname/sharedResource/";
String imageNameForSave = "/qqq.png";
if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
{
Toast.makeText(this, "Your device doesn't have external storage.", Toast.LENGTH_SHORT).show();
return;
}
else
{
Log.d("SD", "YES", null);
dir = new File(Environment.getExternalStorageDirectory()+File.separator+directorySubPath);
if (!dir.exists()){
dir.mkdirs();
}
else {
Log.d("Q-Design:", "Already created", null);
}
}
This is for code convert layout to bitmap image & save.
rLayout.setDrawingCacheEnabled(true);
Bitmap bmp = Bitmap.createBitmap(rLayout.getDrawingCache());
FileOutputStream out = new FileOutputStream(dir+imageNameForSave);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
rLayout.setDrawingCacheEnabled(false);
This is for SHARING that image via Intent:
Uri uri = Uri.parse("file:///" + dir + imageNameForSave);
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/jpg");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Test Mail");
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Data Shared with you...");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share via:"));
Use a dynamic name in String imageNameForSave
Ex. String imageNameForSave = "/qqq" + mydate + ext;

WhatsApp shared image just black

if (Utils.isPackageInstalled(getContext(), "com.whatsapp")) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
Bitmap bitmap = Utils.screenShotBitmap(getActivity());
Utils.saveImage(getActivity(), bitmap, bet.getID() + ".jpeg");
File file = new File(getActivity().getFilesDir(), bet.getID() + ".jpeg");
if (file.exists()) {
Log.i("share", "file exists");
Log.i("share", Uri.fromFile(file).toString());
}
sendIntent.putExtra(Intent.EXTRA_TEXT, "Share text");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
sendIntent.setType("image/*");
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
}
// ...
public static Bitmap screenShotBitmap(Activity activity) {
return Falcon.takeScreenshotBitmap(activity);
}
public static void saveImage(Context context, Bitmap b, String name){
FileOutputStream out;
try {
out = context.openFileOutput(name, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Log-Output:
03-25 17:13:24.328 26417-26417/x.x.x I/share: file exists
03-25 17:13:24.328 26417-26417/x.x.x I/share: file:///data/data/x.x.x/files/4b00abc2-7aae-4234-945b-59905306ad4a.jpeg
Result:
Bitmap bitmap = Utils.screenShotBitmap(getActivity()); seems to work fine and return a correct Bitmap, because I can share it without problems to facebook.
because I can share it without problems to facebook
Not with that code.
You are writing the file to internal storage. Neither Facebook nor WhatsApp has access to your portion of internal storage. Plus, using file: Uri values is being phased out.
The correct long-term answer is for you to use a ContentProvider to publish the bitmap, such as using FileProvider. In the short term, you can probably get away with writing to external storage, such as getExternalFilesDir().
Also note that ACTION_SEND recipients do not need to honor both EXTRA_TEXT and EXTRA_STREAM, but only one or the other.

How to share image that is downloaded and cached with Volley?

In my app I download images from server using Volley and its ImageLoader (with BitmapLruCache). I want to create a share option, researched a little bit, and found that share intent can only share localy stored images. First question, is this right?
Second, if that is right, what should I do? Should I download image again and save it to local storage? Or put it in MediaStore? Or I can pull image from cache and share cached version? What are the best practices?
Any suggestion is welcome, or code snippet.
What I did is made another request for getting the image, and added an ImageListener which provides ImageContainer containing bitmap.
MyApplication.getImageLoader(activity).get(imageURL, new ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {}
#Override
public void onResponse(ImageContainer response, boolean isImmediate) {
Bitmap mBitmap = response.getBitmap();
ContentValues image = new ContentValues();
image.put(Media.MIME_TYPE, "image/jpg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, image);
try {
OutputStream out = getContentResolver().openOutputStream(uri);
boolean success = mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.close();
if (!success) {
} else {
imageUri = uri;
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Create the share Intent
Intent shareIntent = ShareCompat.IntentBuilder.from(activity).setType("image/jpg").setText(shareText).getIntent();
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
mShareActionProvider.setShareIntent(shareIntent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
As image is already downloaded and cached (using BitmapLRU cache and ImageLoader), this new request gives me bitmap from cache so no new network data is made.

How do I save an ImageView as an image?

I have an ImageView with a share intent( which works great, brings up all the apps I can share the image with), however, I can not share the photo because it has no path on my phone. How do I go about saving the ImageView on my phone? Below is my code.
public void taptoshare(View v)
{
View content = findViewById(R.id.myimage);
content.setDrawingCacheEnabled(true);
Bitmap bitmap = content.getDrawingCache();
File file = new File("/DCIM/Camera/image.jpg");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 100, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
Intent shareIntent = new Intent(Intent.ACTION_SEND);
Uri phototUri = Uri.parse("/DCIM/Camera/image.jpg");
shareIntent.setData(phototUri);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
startActivity(Intent.createChooser(shareIntent, "Share Via"));
}
}
UPDATE
Ok, so I figured it out. Now I have a new question, how would I go about saving this image to a new folder?
When saving and loading, you need to get the root path of the system, first. This is how I'd do it.
File root = Environment.getExternalStorageDirectory();
File cachePath = new File(root.getAbsolutePath() + "/DCIM/Camera/image.jpg");
I've come across a couple solutions which are not solving this problem.
Here is a solution that worked for me. One gotcha is you need to store the images in a shared or non app private location (http://developer.android.com/guide/topics/data/data-storage.html#InternalCache)
Many suggestions say to store in the Apps "private" cache location but this of course is not accessable via other external applications, including the generic Share File intent which is being utilised. When you try this, it will run but for example dropbox will tell you the file is no longer available.
/* STEP 1 - Save bitmap file locally using file save function below. */
localAbsoluteFilePath = saveImageLocally(bitmapImage);
/* STEP 2 - Share the non private Absolute file path to the share file intent */
if (localAbsoluteFilePath!=null && localAbsoluteFilePath!="") {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
Uri phototUri = Uri.parse(localAbsoluteFilePath);
File file = new File(phototUri.getPath());
Log.d("file path: " +file.getPath(), TAG);
if(file.exists()) {
// file create success
} else {
// file create fail
}
shareIntent.setData(phototUri);
shareIntent.setType("image/png");
shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
activity.startActivityForResult(Intent.createChooser(shareIntent, "Share Via"), Navigator.REQUEST_SHARE_ACTION);
}
/* SAVE IMAGE FUNCTION */
private String saveImageLocally(Bitmap _bitmap) {
File outputDir = Utils.getAlbumStorageDir(Environment.DIRECTORY_DOWNLOADS);
File outputFile = null;
try {
outputFile = File.createTempFile("tmp", ".png", outputDir);
} catch (IOException e1) {
// handle exception
}
try {
FileOutputStream out = new FileOutputStream(outputFile);
_bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
} catch (Exception e) {
// handle exception
}
return outputFile.getAbsolutePath();
}
/* STEP 3 - Handle Share File Intent result. Need to remote temporary file etc. */
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// deal with this with whatever constant you use. i have a navigator object to handle my navigation so it also holds all mys constants for intents
if (requestCode== Navigator.REQUEST_SHARE_ACTION) {
// delete temp file
File file = new File (localAbsoluteFilePath);
file.delete();
Toaster toast = new Toaster(activity);
toast.popBurntToast("Successfully shared");
}
}
/* UTILS */
public class Utils {
//...
public static File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file =
new File(Environment.getExternalStorageDirectory(), albumName);
if (!file.mkdirs()) {
Log.e(TAG, "Directory not created");
}
return file;
}
//...
}
I hope that helps someone.

Categories

Resources