Search code examples
androidwhatsappandroid-sharing

Not able to share an Image on Whatsap


I am writing an app to share image. I wrote the code but getting problems. What I am doing 1: Saving the image temporarily in Internal Stoarge 2: Passing the URI to share the image.

Image is successfully saved in internal storage but not getting share on whatsapp. When I share it on whatsapp, Whatsapp get opens, I select recipient, whatsapp processes it and says "Retry".

Code:

    public void shareImage(View V)
    {

        Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.download);
        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("image/jpeg");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
          icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

        File file =  new File(Environment.getExternalStorageDirectory()
            + File.separator + "myDownloadedImage.jpg");


     try
     {
      file.createNewFile();
      FileOutputStream fo = new FileOutputStream(file);
      fo.write(bytes.toByteArray());
      fo.close();
     } catch (IOException e) {         
      Toast.makeText(this, "Some error in Writing"+e.getMessage(), Toast.LENGTH_LONG).show();
          e.printStackTrace();
    }

   Uri downloadLocation=Uri.fromFile(file);
   share.putExtra(Intent.EXTRA_STREAM, downloadLocation);
   startActivity(Intent.createChooser(share, "Share Image"));

}

Image succesfully get saved on internal storage but not getting shared on whatsapp.

The screenshot is below. We can see images are not shared successfully.

enter image description here


Solution

  • Use below code to fetch image and make uri:

                    File file =  new File(Environment.getExternalStoragePublicDirectory(  
                        Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
                    file.getParentFile().mkdirs();
                    FileOutputStream out = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
                    out.close();
                    bmpUri = Uri.fromFile(file);
    

    Now pass the bmpUri in:

    shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
    

    This should make your image share.