Android 分享来自 url 的图像

2024-01-11

我想使用以下代码共享图像:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri imageUri = Uri.parse("http://stacktoheap.com/images/stackoverflow.png");
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(sharingIntent);

我制作了一个调用上面代码的按钮。共享意图已打开,但如果我单击“通过彩信共享”,我会收到:“无法将此图片添加到您的消息中”。如果 Facebook 我只有一个文本区域,没有我的图片。


@eclass 答案的改编版本,不需要使用 ImageView:

Use Picasso http://square.github.io/picasso/将 url 加载到位图中

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) { }
    });
}

将位图转换为 Uri

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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android 分享来自 url 的图像 的相关文章