Sharing images from drawable by saving in internal storage

914 Views Asked by At

I have about 10 images in my app and they are in drawable resorses, not downloading from server.

I need to share this images.

I've got solution like this: convert drawable to file, save it and share file from folder.

Everething is ok with External Storage, when I got a sd-card. But when I am using Nexus 5, for example(Internal Storage) it save some file, but doesn't share it, because of unnormal format.

Please, help me with internal storage or with sharing from drawable.

private void shareit()
    {

        Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.son); 

        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("image/jpeg");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

        File f;             

        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // We can read and write the media
            f=new File(Environment.getExternalStorageDirectory() + File.separator + "son.jpg");
        }
        else{
            f = new File(getActivity().getApplicationContext().getCacheDir(), "son.jpg");
            if(f.exists()){
                Log.i("imageExistsInternal", "file is complete");
            }
        }
        if(!f.exists())
            f.mkdir();
        share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
        startActivity(Intent.createChooser(share, "Share Image"));
    }
1

There are 1 best solutions below

1
On

In your code above, you didn't write your image to the file. If the image doesn't exist, a directory will be created, so the format is wrong.

  if(!f.exists())
      f.mkdir();

You need to change like this

if (!f.exists()) {
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(f);
            outputStream.write(bytes.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }