【问题标题】:Android Eclipse: Sharing image to facebook without mediaStore.Insert()Android Eclipse:在没有 mediaStore.Insert() 的情况下将图像共享到 facebook
【发布时间】:2025-12-18 08:40:02
【问题描述】:

我想使用 Intent 将屏幕截图分享到 Facebook、Twitter 等。我找到了通过将图像插入媒体存储然后获取该图像的 URI 来实现此目的的代码示例。但是,我不想用这些无用的图像堵塞用户的设备,我也不想请求访问外部权限,因为我不会在应用程序的其他任何地方使用它。有没有办法构建意图,使其无需 URI 即可共享图像?像直接传递位图,还是压缩成.png后传递?或者有没有办法为内存中保存的位图构建一个 URI,而无需先将其制成文件?

我现在正在使用这个:

public void shareScore(String scoreTextString, String scoreString, Uri screenShotUri){      
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);      
        sharingIntent.setType("image/png");     
        sharingIntent.putExtra(android.content.Intent.EXTRA_STREAM, screenShotUri);     
        startActivity(Intent.createChooser(sharingIntent, "Share Via..."));
    }

public Bitmap takeScreenshot(GL10 mGL) {        
    final int mWidth =  this.getGlView().getWidth();
    final int mHeight = this.getGlView().getHeight();
    IntBuffer ib = IntBuffer.allocate(mWidth * mHeight);
    IntBuffer ibt = IntBuffer.allocate(mWidth * mHeight);
    mGL.glReadPixels(0, 0, mWidth, mHeight, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, ib);

    // Convert upside down mirror-reversed image to right-side up normal image.
    for (int i = 0; i < mHeight; i++) {
        for (int j = 0; j < mWidth; j++) {
            ibt.put((mHeight - i - 1) * mWidth + j, ib.get(i * mWidth + j));
        }
    }       

    Bitmap mBitmap = Bitmap.createBitmap(mWidth, mHeight,Bitmap.Config.ARGB_8888);
    mBitmap.copyPixelsFromBuffer(ibt);      
    return mBitmap;
}

private Uri getImageUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.PNG, 100, bytes);
        String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);     
        return Uri.parse(path);
    }

private void share(){
    String scoreTextString = "I set a new high score on Butterfly Bonanza!";
    String scoreString = "Score :" + Integer.toString(score);               
    Uri screenShotUri = getImageUri(GLGame.class.cast(game), ButterflyBonanza.class.cast(game).getScreenShot());
    ButterflyBonanza.class.cast(game).shareScore(scoreTextString, scoreString, screenShotUri);
}

【问题讨论】:

  • 你应该尽量简洁。
  • 谢谢 Anubian,我已经编辑了我的问题并提供了代码 sn-ps

标签: android eclipse facebook android-intent bitmap


【解决方案1】:

URI 总是指向一个文件,因此无法为内存中的位图创建 URI。

正如您所指出的,您可以将图像直接附加到意图,如下所示:

 ByteArrayOutputStream bos = new ByteArrayOutputStream();  
 yourBitmap.compress(CompressFormat.PNG, 0, bos);  


 Intent intent = new Intent(); 
 intent.setAction(Intent.ACTION_SEND); 
 intent.setType("*/*"); 
 intent.putExtra(Intent.EXTRA_STREAM, bos.toByteArray());
 startActivity(intent); 

【讨论】:

  • 我读到这种方式发送很慢?这是真的?之后我会尝试编辑评论
  • intent.setType("image/png"); ^^我改成这个,因为当我尝试使用这个解决方案运行时,最初得到烤面包要求照片,在使用选择器选择 facebook 后,它会导致 facebook 应用程序崩溃
  • 此解决方案似乎不适用于与不是我自己的活动共享图像。
最近更新 更多