从Android应用程序分享图像

3
我是一名有用的助手,可以为您进行文本翻译。以下是您需要翻译的内容:

我正在尝试从我的Android应用程序共享图像。我想将其作为电子邮件附件和WhatsApp上的照片发送。

代码如下:

String imageUrl = Path to image (eg. sdcard/pictures/image1.jpg);
shareImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Uri uriToImage= Uri.parse(imageUrl);
                    Log.d("Image", ""+uriToImage);
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
                    shareIntent.setType("image/*");
                    startActivity(Intent.createChooser(shareIntent, "Share image:"));
                }
            });

正在发生的事情是:
  1. 在 WhatsApp 上,我可以轻松地分享图片。
  2. 在 Gmail 上,它说无法发送附件。
  3. 在 Hangouts 上,我得到了一个弹出消息,上面写着“找不到照片”
  4. 在 Facebook 上,帖子没有附带图像,但我可以发布。
  5. 在 Facebook Messenger 上,它在打开之前就崩溃了。
我遵循的教程在这里给出:这里。我实现的是教程中的“发送二进制内容”部分。
我尝试的另一件事是将图像设置为 ImageView 并查看是否显示。图像被正确显示。此外,日志消息打印了图像的正确路径。
我还阅读并尝试了以下问题的答案:问题 1问题 2,但均无效。
我哪里做错了?

使用真实的 MIME 类型。image/* 不是真正的 MIME 类型。如果您的图像是 JPEG,请使用 image/jpeg - CommonsWare
imageUrl 的实际值是什么?您在虚假代码列表中嵌入的内容不是有效的 Uri。您的 Log.d() 语句实际记录了什么? - CommonsWare
@CommonsWare 好的。日志信息是:/storage/emulated/0/app_pictures/2/back.jpg这是错误的Uri吗?如果是,为什么? - praxmon
@CommonsWare 一个正确的Uri长什么样子? - praxmon
对于文件,它将具有“file”方案。正如Mayur建议的那样,使用fromFile()File对象创建一个正确的Uri - CommonsWare
显示剩余3条评论
2个回答

5

试试这个:

try
                {
                    File myFile = new File(share_image_path);
                    MimeTypeMap mime = MimeTypeMap.getSingleton();
                    String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
                    String type = mime.getMimeTypeFromExtension(ext);
                    Intent sharingIntent = new Intent("android.intent.action.SEND");
                    sharingIntent.setType(type);
                    sharingIntent.putExtra("android.intent.extra.STREAM", Uri.fromFile(myFile));
                    startActivity(Intent.createChooser(sharingIntent, "Share using"));
                }
                catch (Exception e)
                {
                    Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }

0

是的,@CommonsWare的回答是正确的,你在Intent.putExtra()中漏掉了Schema,这就是为什么它无法在其他社交媒体平台上读取你的图片。 以下是我的解决方案

 Uri fileUri = Uri.fromFile(new File(imagePath));

 //No need to do mimeType work or ext 

 Intent intent = new Intent(Intent.ACTION_SEND);
 intent.putExtra(Intent.EXTRA_STREAM, fileUri);
 intent.setType("image/*");
 startActivity(Intent.createChooser(intent, "Share Image:"));

顺便提一句,它可以在所有提到的平台上运行

   Uri image_uri = Uri.parse("file://"+imagePath);

创建Uri并将其传递给意图的另一种方法

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接