2017-03-18 37 views
0

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

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例外

回答

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

它在'b.compress崩溃(Bitmap.CompressFormat.JPEG,100,字节);' – almiters

+0

刚才我改变了答案。尝试一次更新的代码 –