从网址分享图片

时间:2017-03-18 07:23:50

标签: android

我想分享一个我从Json那里取的图像。经过多次尝试,我终于用这段代码结束了。它运行良好,直到我打开whatsapp并选择我想要分享的联系人,图像不会从那里加载,当我点击提交时,它说共享失败。

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 = new FileOutputStream(file); 将显示错误消息,然后我必须添加try / catch,应用程序崩溃说Nullpoint异常

1 个答案:

答案 0 :(得分:0)

试试这段代码:

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"));