Android 从url共享图像

Android 从url共享图像,android,Android,我正在尝试共享一个从Json获取的图像。经过多次尝试,我终于用这段代码结束了。在我打开whatsapp并选择要共享的联系人之前,它工作得很好,图像不会从那里加载,当我单击submit时,它显示共享失败 Drawable drawable1 = imageViewPreview.getDrawable(); Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.id.image_preview); File file =

我正在尝试共享一个从Json获取的图像。经过多次尝试,我终于用这段代码结束了。在我打开whatsapp并选择要共享的联系人之前,它工作得很好,图像不会从那里加载,当我单击submit时,它显示共享失败

Drawable drawable1 = imageViewPreview.getDrawable();
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.id.image_preview);
File file = new File(SlideshowDialogFragment.this.getCacheDir(), String.valueOf(largeIcon + ".png"));

// FileOutputStream fOut = new FileOutputStream(file);
// largeIcon.compress(Bitmap.CompressFormat.JPEG, 100, fOut);

file.setReadable(true, false);
final 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/png");
startActivity(intent);
如果我删除这些评论

FileOutputStream fOut=新的FileOutputStream(文件)
将显示错误消息,我必须添加try/catch,然后应用程序崩溃,并显示Nullpoint exception

请尝试以下代码:

Bitmap bitmap = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "photo.jpg");
try {
    f.createNewFile();
    FileOutputStream fo = new FileOutputStream(f);
    fo.write(bytes.toByteArray());
} catch (IOException e) {                       
        e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/photo.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));

请参阅此链接以获取完整答案