简体   繁体   English

如何与其他应用程序共享图像意图(在whatsApp和其他应用程序中共享图像)?

[英]How to share image intent to other apps(share image in apps like whatsApp and other apps)?

I tried sharing the images from my app to other apps but a toast is displayed = "file not sent". 我尝试将图像从我的应用程序共享到其他应用程序,但是显示了敬酒=“文件未发送”。 not sure what to do. 不知道该怎么办。 down below I have posted the code that I am using to share image 在下面,我已经发布了用于共享图片的代码

 @Override
    public void onWhatEverClick(int position) {
        Toast.makeText(this, "Normal click at position: " + position, Toast.LENGTH_SHORT).show();
        try {
            Upload selectedItem = mUploads.get(position);

            final String selectedkey = selectedItem.getKey();
            StorageReference imgRef = mStorage.getReferenceFromUrl(selectedItem.getImageUrl());
            String url = selectedItem.getImageUrl();
            String imageString = url.toString();
            URI uri = new URI(imageString);
            final Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("image/jpg");
            shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
            startActivity(Intent.createChooser(shareIntent, "Share image using"));
        }


        catch (Exception e)
        {

        }
    }

You can't directly share the remote image using just it's url, you'll need to download it before sharing. 您不能仅使用URL直接共享远程图像,而是需要先下载它才能共享。

The 'easy' way of doing this would be to use a library like Picasso or Glide to download the file into a bitmap, store it in the ExternalFiles and get the URI from the file which can then be shared. 实现此目的的“简便”方法是使用PicassoGlide之类的库将文件下载到位图中,将其存储在ExternalFiles中,然后从文件中获取URI ,然后可以将其共享。

public void shareItem(String url) {
    Picasso.with(getApplicationContext()).load(url).into(new Target() {
        @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("image/*");
            i.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(bitmap));
            startActivity(Intent.createChooser(i, "Share Image"));
        }
        @Override public void onBitmapFailed(Drawable errorDrawable) { }
        @Override public void onPrepareLoad(Drawable placeHolderDrawable) { }
    });
}

public Uri getLocalBitmapUri(Bitmap bmp) {
    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;
}

Example code referenced from this stackoverflow answer . 从此stackoverflow答案引用的示例代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM