Share An Image Without Saving it in Android

share-image-without-saving logicchip thumb

As a matter of fact sometimes we want to share images without saving it. Images from internet or locally generated images.For example  whatsapp profile pictures. You can share it, but it’s only visible in gallery when we saved it. However we are using bitmap generated from linear-layout to share.

In fact  sharing an image without saving it is by using cache memory. Consequently we can share it like an uri. On the other hand we can simply store the image in cache and use the uri for sharing.

share-image-without-saving logicchip 1

Furthermore we are saving bitmap to cache and use it for sharing. In fact a previous post explain how to convert view to bitmap.Binary data is shared using the ACTION_SEND action combined with setting the appropriate MIME type and placing the URI to the data in an extra named EXTRA_STREAM. This is commonly used to share an image but can be used to share any type of binary content.

You can use a MIME type of "*/*", but this will only match activities that are able to handle generic data streams.

In conclusion the receiving application needs permission to access the data the Uri points to.

Similarly we don’t need any special permission to store data in cache memory.

Adding Permission

Add these permissions in the manifest file.

OnClickShare

However below is the onclick method for share button. Create a method with view as argument then specify it in the xml file.

Creating bitmap from view

For instance method creates bitmap from view or any layout extending view.If the background is empty it set’s white color as background.

MainActivity.java

This class file contain both methods, we don’t use onclick listener or implement onclick listener in order to reduce code. Because the click is coded directly to the xml file using onclick.

activity_main.xml

Still the  project require an user interface. Even though below xml file is just for showing how this work.

Even so “Share An Image Without Saving it in Android” is explained above you can still download it from here, You can modify the code us u like. In like manner feel free to comment your doubt’s below. Does our tutorials help you then help as spread the word, like and share.

 

You Might Also Like

31 Replies to “Share An Image Without Saving it in Android”

  1. just awesome man keep doing good work i searched for the code to work for 15 days and its working now wow man

  2. what if the images inside layout pass into new activity ?*cuz later i want to fill the attributes likes name, etc and finally upload to firebase* how to pass it ? I need it for my project ~

      1. File file = new File(this.getExternalCacheDir(),”logicchip.png”); this line is for single image,change the name “logicchip.png” for each image.

        1. thanks…this is the code i’m using…I’m certain that there is some fundamental flaw with this…I’m not really an expert…please suggest……………..

          package com.fsa.fonline;

          import android.content.Intent;
          import android.graphics.Bitmap;
          import android.graphics.Canvas;
          import android.graphics.Color;
          import android.graphics.drawable.Drawable;
          import android.net.Uri;
          import android.support.v7.app.AppCompatActivity;
          import android.os.Bundle;
          import android.view.View;
          import android.widget.LinearLayout;

          import java.io.File;
          import java.io.FileOutputStream;

          public class ShareImages extends AppCompatActivity {

          LinearLayout idForSaveView;
          LinearLayout idForSaveView1;

          static int CODE_FOR_RESULT=981;

          @Override
          protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_share_images);

          idForSaveView=(LinearLayout)findViewById(R.id.idForSaveView);
          idForSaveView1=(LinearLayout)findViewById(R.id.idForSaveView1);
          }

          public void OnClickShare(View view){

          Bitmap bitmap =getBitmapFromView(idForSaveView);
          try {
          //File file = new File(this.getExternalCacheDir(),File.separator+ “logicchip.png”);
          File file = new File(this.getExternalCacheDir(),”logicchip.png”);
          // File file = new File(this.getCacheDir(),File.separator+ “logicchip.png”);
          FileOutputStream fOut = new FileOutputStream(file);
          bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
          fOut.flush();
          fOut.close();
          file.setReadable(true, false);
          final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
          intent.setType(“image/png”);
          //startActivity(Intent.createChooser(intent, “Share image via”));
          startActivityForResult(Intent.createChooser(intent, “Share image via”),CODE_FOR_RESULT);
          } catch (Exception e) {
          e.printStackTrace();
          }

          Bitmap bitmap1 =getBitmapFromView(idForSaveView1);
          try {
          //File file = new File(this.getExternalCacheDir(),File.separator+ “logicchip.png”);
          File file = new File(this.getExternalCacheDir(),”logicchip1.png”);
          // File file = new File(this.getCacheDir(),File.separator+ “logicchip.png”);
          FileOutputStream fOut = new FileOutputStream(file);
          bitmap1.compress(Bitmap.CompressFormat.PNG, 100, fOut);
          fOut.flush();
          fOut.close();
          file.setReadable(true, false);
          final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
          intent.setType(“image/png”);
          //startActivity(Intent.createChooser(intent, “Share image via”));
          startActivityForResult(Intent.createChooser(intent, “Share image via”),CODE_FOR_RESULT);
          } catch (Exception e) {
          e.printStackTrace();
          }
          }

          //create bitmap from view and returns it
          private Bitmap getBitmapFromView(View view) {
          //Define a bitmap with the same size as the view
          Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
          //Bind a canvas to it
          Canvas canvas = new Canvas(returnedBitmap);
          //Get the view’s background
          Drawable bgDrawable =view.getBackground();
          if (bgDrawable!=null) {
          //has background drawable, then draw it on the canvas
          bgDrawable.draw(canvas);
          } else{
          //does not have background drawable, then draw white background on the canvas
          canvas.drawColor(Color.WHITE);
          }
          // draw the view on the canvas
          view.draw(canvas);
          //return the bitmap
          return returnedBitmap;
          }
          }

          1. Wait….its working fine for me now…tried with two images…however, I still feel what I’m doing is not the right way and this is just a hack…please suggest…. Code Below….

            package com.fsa.fonline;

            import android.content.Intent;
            import android.graphics.Bitmap;
            import android.graphics.Canvas;
            import android.graphics.Color;
            import android.graphics.drawable.Drawable;
            import android.net.Uri;
            import android.support.v7.app.AppCompatActivity;
            import android.os.Bundle;
            import android.view.View;
            import android.widget.LinearLayout;

            import java.io.File;
            import java.io.FileOutputStream;

            public class ShareImages extends AppCompatActivity {

            LinearLayout idForSaveView;
            LinearLayout idForSaveView1;

            static int CODE_FOR_RESULT=981;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_share_images);

            idForSaveView=(LinearLayout)findViewById(R.id.idForSaveView);
            idForSaveView1=(LinearLayout)findViewById(R.id.idForSaveView1);
            }

            public void OnClickShare(View view) {

            Bitmap bitmap = getBitmapFromView(idForSaveView);
            try {
            //File file = new File(this.getExternalCacheDir(),File.separator+ “logicchip.png”);
            File file = new File(this.getExternalCacheDir(), “logicchip.png”);
            // File file = new File(this.getCacheDir(),File.separator+ “logicchip.png”);
            FileOutputStream fOut = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            fOut.flush();
            fOut.close();
            file.setReadable(true, false);
            final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
            intent.setType(“image/png”);
            //startActivity(Intent.createChooser(intent, “Share image via”));
            startActivityForResult(Intent.createChooser(intent, “Share image via”), CODE_FOR_RESULT);
            } catch (Exception e) {
            e.printStackTrace();
            }

            }

            public void OnClickShare1(View view) {

            Bitmap bitmap1 =getBitmapFromView(idForSaveView1);
            try {
            //File file = new File(this.getExternalCacheDir(),File.separator+ “logicchip.png”);
            File file = new File(this.getExternalCacheDir(),”logicchip1.png”);
            // File file = new File(this.getCacheDir(),File.separator+ “logicchip.png”);
            FileOutputStream fOut = new FileOutputStream(file);
            bitmap1.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            fOut.flush();
            fOut.close();
            file.setReadable(true, false);
            final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
            intent.setType(“image/png”);
            //startActivity(Intent.createChooser(intent, “Share image via”));
            startActivityForResult(Intent.createChooser(intent, “Share image via”),CODE_FOR_RESULT);
            } catch (Exception e) {
            e.printStackTrace();
            }
            }

            //create bitmap from view and returns it
            private Bitmap getBitmapFromView(View view) {
            //Define a bitmap with the same size as the view
            Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
            //Bind a canvas to it
            Canvas canvas = new Canvas(returnedBitmap);
            //Get the view’s background
            Drawable bgDrawable =view.getBackground();
            if (bgDrawable!=null) {
            //has background drawable, then draw it on the canvas
            bgDrawable.draw(canvas);
            } else{
            //does not have background drawable, then draw white background on the canvas
            canvas.drawColor(Color.WHITE);
            }
            // draw the view on the canvas
            view.draw(canvas);
            //return the bitmap
            return returnedBitmap;
            }
            }

          2. you can allocate image name “logichip.png in this case” dynamically. Its just a name, may be use your id as image name.

  3. I am loading image in ImageView using Picasso. I want to share that image without saving in android. When I used above code, Picasso might be not loading image and the layout is showing white. What is the solution for that Akhil?

    1. Check permissions, make sure the required permissions are granted. Can you share the screenshots of code, or anything that i can work with ?

  4. I am using Picasso for loading image in ImageView. I want to share that images without saving it. I tried the above code but then Picasso might be not loading image in ImageView. What is the Problem Akhil?

      1. LinearLayout idForSaveView;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_wallpaper);
        idForSaveView=(LinearLayout)findViewById(R.id.idForSaveView);
        imageView=(ImageView)findViewById(R.id.imageThumb);

        Picasso.with(getBaseContext())
        .load(Common.select_background.getImageLink())
        .networkPolicy(NetworkPolicy.OFFLINE)
        .placeholder( R.drawable.circular_progress_view )
        .into(imageView, new Callback() {
        @Override
        public void onSuccess() {

        }
        @Override
        public void onError() {
        Picasso.with(getBaseContext())
        .load(Common.select_background.getImageLink())
        .error(R.drawable.ic_image_black_24dp)
        .into(imageView, new Callback() {
        @Override
        public void onSuccess() {

        }
        @Override
        public void onError() {
        Log.e(“ERROR_STATUS”,”Couldn’t load image”);
        }
        });
        }
        });
        }

        public void instaOnClick(View view) {
        loadingcardholder.setVisibility(View.VISIBLE);
        Bitmap bitmap = getBitmapFromView(idForSaveView);
        try {
        File file = new File(this.getExternalCacheDir(), “logicchip.png”);
        FileOutputStream fOut = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
        file.setReadable(true, false);
        final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        intent.setType(“image/*”);
        intent.setPackage(“com.instagram.android”);
        try {
        startActivity(intent);
        } catch (Exception e) {
        Toast.makeText(getApplicationContext(), “Instagram App not installed!”, Toast.LENGTH_LONG).show();
        }
        } catch (Exception e) {
        e.printStackTrace();
        }

        private Bitmap getBitmapFromView(View view) {
        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(returnedBitmap);
        Drawable bgDrawable =view.getBackground();
        if (bgDrawable!=null) {
        //has background drawable, then draw it on the canvas
        bgDrawable.draw(canvas);
        } else{
        //does not have background drawable, then draw white background on the canvas
        canvas.drawColor(Color.WHITE);
        }
        view.draw(canvas);
        return returnedBitmap;
        }

        //xml

          1. I have solved it.

            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());

            Added this in onCreate() and pass the ImageView in which I am loading the image to the Bitmap getBitmapFromView(View view). And it works!

            Thank you so much Akhil ! I was stuck there from last 1 week. Thank you again!

    1. simple just load your external image to an imageview,here we are generating bitmap from view.A view can be ImageView,LinearLayout or any other.

  5. Hello:
    If I create a qrcode , how can I send qrcode without saving it ?
    BarcodeEncoder encoder = new BarcodeEncoder();
    try
    {
    Bitmap bitmap = encoder.encodeBitmap(etContent.getText().toString(), BarcodeFormat.QR_CODE, 1500, 1500);
    try
    {
    File file = new File(this.getExternalCacheDir(),”temp.png”);

    is not working..?

    1. maybe by first create qr code load it to an imageview,turn the imageview to
      Bitmap bitmap =getBitmapFromView(idForSaveView);
      try {
      File file = new File(this.getExternalCacheDir(),”logicchip.png”);
      FileOutputStream fOut = new FileOutputStream(file);
      bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
      fOut.flush();
      fOut.close();
      file.setReadable(true, false);
      final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
      intent.setType(“image/png”);
      startActivity(Intent.createChooser(intent, “Share image via”));
      } catch (Exception e) {
      e.printStackTrace();
      }

Leave a Reply