android share image from url

前端 未结 10 1825
攒了一身酷
攒了一身酷 2020-12-01 07:50

I want to share an image using the code:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri imageUri = Uri.parse(\"http://stacktoheap.com/images/stac         


        
相关标签:
10条回答
  • 2020-12-01 08:31
    Picasso.with(applicationContext).load(url).into(object : Target {
                override fun onBitmapLoaded(bitmap: Bitmap, from: Picasso.LoadedFrom?) {
                    val bitmapPath: String =
                        MediaStore.Images.Media.insertImage(contentResolver, bitmap, "ayurved", null)
                    val bitmapUri = Uri.parse(bitmapPath)
                    val shareIntent = Intent(Intent.ACTION_SEND)
                    shareIntent.type = "image/jpeg";
                    shareIntent.putExtra(Intent.EXTRA_STREAM, bitmapUri);
                    startActivity(Intent.createChooser(shareIntent, "ayurved"))
                }
                override fun onBitmapFailed(errorDrawable: Drawable?) {}
                override fun onPrepareLoad(placeHolderDrawable: Drawable?) {}
            })
    
    0 讨论(0)
  • 2020-12-01 08:34

    By using createchooser you can achieve this,

    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    Uri screenshotUri = Uri.parse(path);
    
    sharingIntent.setType("image/png");
    sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
    startActivity(Intent.createChooser(sharingIntent, "Share image using"));
    

    Registering for the Intent

    If you want your app to be listed when this Intent is called, then you have to add an intent filter in your manifest.xml file

     <intent-filter>
     <action android:name="android.intent.action.SEND" />
     <category android:name="android.intent.category.DEFAULT" />
     <data android:mimeType="image/*" />
     </intent-filter>
    
    0 讨论(0)
  • 2020-12-01 08:37

    You need to use a local file. Like this:

          Uri imageUri = Uri.parse("android.resource://your.package/drawable/fileName");
          Intent intent = new Intent(Intent.ACTION_SEND);
          intent.setType("image/png");
    
          intent.putExtra(Intent.EXTRA_STREAM, imageUri);
          startActivity(Intent.createChooser(intent , "Share"));
    

    If your image is on remote server download it to the device first.

    0 讨论(0)
  • 2020-12-01 08:37

    Try this:

    new OmegaIntentBuilder(context)
                    .share()
                    .filesUrls("http://stacktoheap.com/images/stackoverflow.png")
                    .download(new DownloadCallback() {
                        @Override
                        public void onDownloaded(boolean success, @NotNull ContextIntentHandler contextIntentHandler) {
                            contextIntentHandler.startActivity();
                        }
                    });
    

    https://github.com/Omega-R/OmegaIntentBuilder

    0 讨论(0)
  • 2020-12-01 08:37

    Here, i convert the url into imageView using asyncTask and store that into a bitmap. dont forget to add internet permission in manifest.

    public class MainActivity extends AppCompatActivity  {
    
        @SuppressLint("WrongThread")
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button iv1 = findViewById(R.id.shreimage);
            final ImageView imgview= (ImageView)findViewById(R.id.content_image);
            new DownloadImageTask(imgview).execute("https://sample-videos.com/img/Sample-jpg-image-50kb.jpg");
            iv1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Drawable myDrawable = imgview.getDrawable();
                    Bitmap bitmap = ((BitmapDrawable)myDrawable).getBitmap();
                    try{
                        File file = new File(MainActivity.this.getExternalCacheDir(),"myImage.jpeg");
                        FileOutputStream fout = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG,80,fout);
                        fout.flush();
                        fout.close();
                        file.setReadable(true,false);
                        Intent intent = new Intent(Intent.ACTION_SEND);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(file));
                        intent.setType("image/*");
                        startActivity(Intent.createChooser(intent,"Share Image Via"));
                    }catch (FileNotFoundException e){
                        e.printStackTrace();
                        Toast.makeText(MainActivity.this,"File Nott Found",Toast.LENGTH_SHORT).show();
                    }catch (IOException e){
                        e.printStackTrace();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
    
         }
    
    
        private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
            ImageView bmImage;
    
            public DownloadImageTask(ImageView bmImage) {
                this.bmImage = bmImage;
            }
    
            protected Bitmap doInBackground(String... urls) {
                String urldisplay = urls[0];
                Bitmap mIcon11 = null;
                try {
                    InputStream in = new java.net.URL(urldisplay).openStream();
                    mIcon11 = BitmapFactory.decodeStream(in);
                } catch (Exception e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
                return mIcon11;
            }
    
            protected void onPostExecute(Bitmap result) {
                bmImage.setImageBitmap(result);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-01 08:39
       share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    int permissionCheck = ContextCompat.checkSelfPermission(SingleProduct.this,
                            Manifest.permission.READ_EXTERNAL_STORAGE);
    
                    if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                        Log.e("MainActivity ", "P granted");
    
                        bmpUri = getLocalBitmapUri(imageView);
    
                    } else {
                        ActivityCompat.requestPermissions(SingleProduct.this,
                                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                    }
                } else {
                    Log.e("MainActivity", "Lower Than MarshMallow");
                    bmpUri = getLocalBitmapUri(imageView);
                }
    
                if (bmpUri != null) {
                    // Construct a ShareIntent with link to image
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    shareIntent.setType("image/*");
                    startActivity(Intent.createChooser(shareIntent, "Share Image"));
                } else {
                    Toast.makeText(SingleProduct.this, "Sharing Failed !!", Toast.LENGTH_SHORT).show();
                }
            }
        });
    

     public Uri getLocalBitmapUri(ImageView imageView) {
        Drawable drawable = imageView.getDrawable();
        Bitmap bmp = null;
        if (drawable instanceof BitmapDrawable) {
            bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
        } else {
            return null;
        }
        Uri bmpUri = null;
        try {
            File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
            FileOutputStream out = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();
    
           bmpUri = Uri.fromFile(file);
    
    
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bmpUri;
    }
    

    //for oreo add below code in manifest under application tag
    
     <provider
            android:name=".utility.GenericFileProvider"
            android:authorities="${applicationId}.your package 
         name.utility.GenericFileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>
    

    create class that extends FileProvider
    
    public class MyFileProvider extends FileProvider {
    
    }
    

    for oreo add this code
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                bmpUri = FileProvider.getUriForFile(this, 
          this.getApplicationContext().getPackageName() + 
        ".your package name.GenericFileProvider", file);
            } else {
                bmpUri = Uri.fromFile(file);
            }
    

    finally add provider_paths.xml in res/xml 
    
       <paths xmlns:android="http://schemas.android.com/apk/res/android">
       <external-path name="external_files" path="."/>
       </paths>
    

    thats all

    0 讨论(0)
提交回复
热议问题