Search code examples
androidandroid-intentandroid-sharing

How can i send image with text with share


Currently i am using the below code for sharing text:

Intent i = new Intent(android.content.Intent.ACTION_SEND);
    i.setType("text/plain");

    i.putExtra(android.content.Intent.EXTRA_TEXT, "This is tesing");

    startActivity(Intent.createChooser(i, "Share via"));

From this i can able to share text on any social media platform.

But i want to also share the image with this and my image is in binary form.

InputStream input = new java.net.URL(
                                product.getString("url")).openStream();

 // Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);

So image sharing i have written below code:

i.putExtra(android.content.Intent.EXTRA_TEXT, bitmap);

But it is not working. It shares the text like :- android.graphics.Bitmap@43394c40

So how can i share image also with this?


Solution

  • YOu have to save the bitmap from url into the disk first then use the file to be passed on intent.

        File file = writebitmaptofilefirst("the_new_image","http://www.theimagesource.com/blahblahblah.jpg");
        Uri uri = Uri.fromFile(file);
    
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
    

    Add this method

    public static File writebitmaptofilefirst(String filename, String source) {
        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
        File mFolder = new File(extStorageDirectory + "/temp_images");
        if (!mFolder.exists()) {
            mFolder.mkdir();
        }
        OutputStream outStream = null;
    
    
        File file = new File(mFolder.getAbsolutePath(), filename + ".png");
        if (file.exists()) {
            file.delete();
            file = new File(extStorageDirectory, filename + ".png");
            Log.e("file exist", "" + file + ",Bitmap= " + filename);
        }
        try {
            URL url = new URL(source);
            Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    
            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("file", "" + file);
        return file;
    
    }