how to share gif images using intent sharing to available apps? - android

i want working on sharing .gif with available apps like whatsapp, but unable to get valid Uri of gif present in my drawable resource.
Uri path = Uri.parse("android.resource://my_package_name/" + R.drawable.gif_1);
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/gif");
shareIntent.putExtra(Intent.EXTRA_STREAM, path);
there is lot of solution on sharing images but no solution on gif sharing, Please help

I found my answer, I just created a file with a .gif extension and it worked for me. See the code below:
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) {
}
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"));
}

if you want to take image from internal storage.
//this is method having internal storage path.
private String getFilePath2() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Gifs temp/");
if (!myDir.exists())
myDir.mkdirs();
String fname = "temp_gif";
SimpleDateFormat timeStampFormat = new SimpleDateFormat(
"yyyyMMdd_HHmmss");
Date myDate = new Date();
String filename = timeStampFormat.format(myDate);
File file = new File(myDir, fname + "_" + filename + ".gif");
if (file.exists()) {
file.delete();
}
String str = file.getAbsolutePath();
return str;
}
// Then take image from internal storage into the string.
String st = getFilePath2();
//And share this by this intent
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"));

Related

Having trouble sharing an image with an android intent

I am trying to get a image of a view (constraint-layout) and share it via an android send-intent.
I tried a lot of methods, but until now none have worked.
This is what I have so far:
public void shareStatsImage(){
constraintLayout.setDrawingCacheEnabled(true);
Bitmap bitmap = constraintLayout.getDrawingCache();
File path = null;
try {
path = saveImageToExternal(generateImageTitle(), bitmap);
} catch (IOException e) {
e.printStackTrace();
}
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/png");
final File photoFile = new File(Objects.requireNonNull(getActivity()).getFilesDir(), Objects.requireNonNull(path).getAbsolutePath());
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(photoFile));
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
public static String generateImageTitle(){
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss");
return sdf.format(new Date());
}
public File saveImageToExternal(String imgName, Bitmap bm) throws IOException {
//Create Path to save Image
String appFolder = "test";
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + File.separator + appFolder); //Creates app specific folder
path.mkdirs();
File imageFile = new File(path, imgName+".png"); // Imagename.png
FileOutputStream out = new FileOutputStream(imageFile);
try{
bm.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
out.flush();
out.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(getContext(),new String[] { imageFile.getAbsolutePath() }, null,new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch(Exception e) {
throw new IOException();
}
return imageFile;
}
There are multiple problems with this solution, for example I am getting an error message ("Permission denied for the attachment") when sharing the image to gmail. When uploading the image to google drive I only get an "upload unsuccessful message".
One good thing is that the images seem to appear in the phone's gallery, just not when sharing them via the intent :(
Thanks for your help!
Convert Bitmap to Uri
private Uri getImageUri(Context context, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), inImage, "Image Title", null);
return Uri.parse(path);
}
You can send Image using Uri.
Uri imageUri = set your image Uri;
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.setType("image/jpeg");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "send"));

How to share GIF image in Whatsapp programmatically in Android?

WhatsApp have added new feature display GIF.
if any one know how to share GIF in whatsapp then let me know
Try this....
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) {
}
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"));
}
For share gif on whatsapp
/* Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setPackage("com.whatsapp");
shareIntent.putExtra(Intent.EXTRA_TEXT,title + "\n\nLink : " + link );
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(sharePath));
shareIntent.setType("image/*");
startActivity(shareIntent);*/
You just need to set the type of image intent as gif like below
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/gif");

How to show dialog to set image as wallpaper or profile picture in android?

I have a pic inside my app in raw folder. I want to give option to users to set that image as an wallpaper or profile picture. A dialog should popup when the option is selected. Like this:
I tried showing this dialog with the following code
int resId = R.raw.a_day_without_thinking_mobile;
Resources resources = this.getResources();
Uri sendUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + resources.getResourcePackageName(resId) + '/' + resources.getResourceTypeName(resId) + '/' + resources.getResourceEntryName(resId));
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.setDataAndType(sendUri, "image/jpg");
intent.putExtra("mimeType", "image/jpg");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(intent, "Set As"));
But this showed me a dialog like this:
I don't want to set image directly as wallpaper instead a dialog should be shown from where user can select whether he/she wants to use the image as wallpaper or profile picture.
First you must download image file from raw folder to sd card and then use the sd card file to set the image as wallpaper
int resId = R.raw.a_day_without_thinking_mobile;
String filename = getResources().getResourceEntryName(resId );
String destfolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + "/Motivational Quotes";
createDirIfNotExists(destfolder);
String destinationPath = destfolder +"/"+ filename + ".jpg";
File destination = new File(destinationPath);
InputStream ins = getResources().openRawResource(
getResources().getIdentifier(filename,
"raw", getPackageName()));
try {
copy2(ins,destination);
//Toast.makeText(this, "Image Downloaded", Toast.LENGTH_SHORT).show();
File externalFile=new File(destinationPath);
Uri sendUri2 = Uri.fromFile(externalFile);
Log.d("URI:", sendUri2.toString());
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.setDataAndType(sendUri2, "image/jpg");
intent.putExtra("mimeType", "image/jpg");
startActivityForResult(Intent.createChooser(intent, "Set As"), 200);
} catch (IOException e) {
e.printStackTrace();
}
public void copy2(InputStream src, File dst) throws IOException {
InputStream in = src;
OutputStream out = new FileOutputStream(dst);
//InputStream in = new FileInputStream(src);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
addImageGallery(dst);
}
private void addImageGallery( File file ) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); // setar isso
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
Here is the code that you can use
Remove the put extra from your intent and use the following for data and type
intent.setDataAndType(sendUri, "image/*");

Android: How to share image with Share Option menu>

I am making a drawing app. Now i want to share my Drawing with share option menu. But drawing canvas image is not attaching while sharing.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/menu_item_share"
android:showAsAction="ifRoom"
android:title="Share"
android:actionProviderClass=
"android.widget.ShareActionProvider"/>
Following is a code of java file
public boolean onCreateOptionsMenu(Menu menu) {
/** Inflating the current activity's menu with res/menu/items.xml */
getMenuInflater().inflate(R.menu.share_menu, menu);
/** Getting the actionprovider associated with the menu item whose id is share */
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.menu_item_share).getActionProvider();
/** Setting a share intent */
mShareActionProvider.setShareIntent(getDefaultShareIntent());
return super.onCreateOptionsMenu(menu);
}
private Intent getDefaultShareIntent(){
Bitmap bitmap = drawView.getDrawingCache();
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + UUID.randomUUID().toString()+".png";
File file = new File(path+"/image.png");
System.out.println("path="+path);
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(path);
//Uri screenshotUri = Uri.fromFile(file);
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
return sharingIntent;
}
Please provide me the way to share canvas image with different apps. Thank you
I know it's a late reply. But this may help someone. Here is the code that worked for me.
private Intent getDefaultShareIntent(){
// Save image to external storage before sending. With out saving, I to got a blank screen as attachment.
String imagePath=saveToExternalSorage(mBitmap);
File f=new File(imagePath);
Uri screenshotUri = Uri.fromFile(f);
//Create an intent to send any type of image
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/*");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
return sharingIntent;
}
where
public String saveToExternalSorage(Bitmap b){
// Get path to External Storage
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/"+IMAGE_PATH);
myDir.mkdirs();
// Generating a random number to save as image name
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String timeStamp = new SimpleDateFormat("yyyyMMdd").format(new Date());
String fname = "Image_"+timeStamp+"_"+ n + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
// Tell your media scanner to refresh/scan for new images
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
System.out.println(path);
}
});
return file.getAbsolutePath();
}
I wonder, saving the image before is the only way to share properly.

Attach image from resource with Email Body Android

I have an app in which there is an email section where I have to entered text and image in body. I searched on net but did not find corresponding solution. Any help will would be appreciated.
Here is the View :
BitmapFactory.Options bitmapFatoryOptions=new BitmapFactory.Options();
bitmapFatoryOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;
Bitmap myBitmap=BitmapFactory.decodeResource(getResources(),R.drawable.face4,bitmapFatoryOptions);
File mFile = savebitmap(myBitmap);
Uri u = null;
u = Uri.fromFile(mFile);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("image/*");
Intent.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Send Mail");
emailIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_texthere));
emailIntent.putExtra(Intent.EXTRA_STREAM, u);
startActivity(Intent.createChooser(emailIntent,"Send"));
Code for saveBitmap() Method:
private File savebitmap(Bitmap bmp) {
String temp="SplashItShare";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
String path = Environment.getExternalStorageDirectory()
.toString();
new File(path + "/SplashItTemp").mkdirs();
File file = new File(path+"/SplashItTemp", temp + ".png");
if (file.exists()) {
file.delete();
file = new File(path+"/SplashItTemp", temp + ".png");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
Hope It will work for you.

Categories

Resources