在drawable文件夹中分享一个png图片

13

我正在为此应用程序集成分享功能,使用以下代码:

private void socialShare()
    {
        Uri uri = Uri.parse("android.resource://com.example.myproject/drawable/appicon");
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        shareIntent.putExtra(Intent.EXTRA_TEXT, "sharing myapp");
        shareIntent.setType("image/jpeg");
        startActivity(Intent.createChooser(shareIntent, "Share from"));
    }

如上代码所示,我正在尝试放置drawable文件夹中的png图像,但是该图像无法发送。这是因为setType中使用了image/jpeg吗? 我不能使用jpeg,因为它会失去透明度。能否有人建议我如何分享图片?

以下是我用来将图像从drawable复制到sdcard的代码:

String commonPath = Environment.getExternalStorageDirectory().toString() + "/MyAppFolder"; 
        File direct = new File(commonPath);

        if(!direct.exists())
        {
            if(direct.mkdir()) 
              {
                Log.d("tag","directory created");
               //directory is created;
              }

        }

        Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.sharingimage);
        OutputStream outStream = null;
           File savingFile = new File(commonPath, "shareImage.png");
           if(!savingFile.exists())
           {
               Log.d("tag","file is created");

           try {
                savingFile.createNewFile();
                outStream = new FileOutputStream(savingFile);
                bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                outStream.flush();
                outStream.close();

                Log.d("tag","Saved");

               } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

               } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

               }

            }
6个回答

18

我找到了解决方案,不需要将图像复制到SD卡上。以下是解决方案:

    try {
        Uri imageUri = null;
        try {
            imageUri = Uri.parse(MediaStore.Images.Media.insertImage(this.getContentResolver(),
                    BitmapFactory.decodeResource(getResources(), R.drawable.fragment_menu_logo), null, null));
        } catch (NullPointerException e) {
        }
        String text = getString(R.string.share_text);
        // Launch the Google+ share dialog with attribution to your app.
        Intent shareIntent = new PlusShare.Builder(mActivity)
                .setType("image/*")
                .setText(text)
                .addStream(imageUri)
                .getIntent();
        startActivity(shareIntent);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(mActivity, mActivity.getString(R.string.share_google_plus_not_installed), Toast.LENGTH_LONG).show();
    }

1
@RSenApps我忘记添加捕获NullPointerException(在这里https://dev59.com/bWct5IYBdhLWcg3wQ7My解释了何时可能)。请查看更新的答案。 - Ruslan Mansurov
1
这会使可绘制对象失去其透明度,你找到了处理它的方法吗? - Mohamed Hamdaoui
MediaStore.Images.Media.insertImage已被弃用。 - Abhi

11
Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.xxxx);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/LatestShare.jpg";
OutputStream out = null;
File file=new File(path);
try {
    out = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
    out.flush();
    out.close();
} catch (Exception e) {
    e.printStackTrace();
}
path=file.getPath();
Uri bmpUri = Uri.parse("file://"+path);
Intent shareIntent = new Intent();
shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/jpg");
startActivity(Intent.createChooser(shareIntent,"Share with"));

这对我来说完美地运行,并且这将需要写入权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

将以下这行代码添加至 Android Manifest 中以获取写入权限。


1
您可以使用 getExternalFilesDir(null) 来避免添加写入存储权限。 - shubhamgarg1

10

您可以使用以下方法分享...

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/png");
Uri uri = Uri.parse("android.resource://your package name/"+R.drawable.ic_launcher);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, This is test Sharing");
startActivity(Intent.createChooser(shareIntent, "Send your image"));

经过试验和测试......对我有效


3
不,它不起作用。它说所有物品都无法附加。我测试了 Facebook、Google+、Gmail 和信息应用程序。没有任何作用。 - rick
2
对我不起作用,我找到了其他解决方案,请查看我的帖子并尝试一下。 - Ashok Varma
运行得非常好! - hetsgandhi

6

首先添加权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

从资源中使用位图

Bitmap b =BitmapFactory.decodeResource(getResources(),R.drawable.userimage);
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("image/jpeg");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            String path = MediaStore.Images.Media.insertImage(getContentResolver(),
                    b, "Title", null);
            Uri imageUri =  Uri.parse(path);
            share.putExtra(Intent.EXTRA_STREAM, imageUri);
            startActivity(Intent.createChooser(share, "Select"));

通过蓝牙测试。

运行良好。


java.lang.NullPointerException: 尝试在空对象引用上调用虚拟方法'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' - Nouman Ch
//打开共享表单 Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.ic_14_cold_turkey); Intent share = new Intent(Intent.ACTION_SEND); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); b.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), b, "ColdTurkey", null); - Nouman Ch
1
Uri imageUri = Uri.parse(path); share.putExtra(Intent.EXTRA_STREAM, imageUri); share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); share.setType("image/png"); startActivity(share); - Nouman Ch

2
不需要权限。不需要实现内容提供程序。
以下是您需要的内容:
清单文件:
        <provider
            android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}"
            android:exported="false" android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" />
        </provider>

res/xml/provider_paths.xml

<paths>
    <cache-path
        name="cache_root" path="." />
</paths>

使用其Intent的代码:

@WorkerThread
fun shareDrawable(context: Context, @DrawableRes resourceId: Int, fileName: String): Intent {
    val bitmap = ResourcesCompat.getDrawable(context.resources, resourceId, null)!!.toBitmap()
    val outputFile = File(context.cacheDir, "$fileName.png")
    val outPutStream = FileOutputStream(outputFile)
    bitmap.compress(CompressFormat.PNG, 100, outPutStream)
    outPutStream.flush()
    outPutStream.close()
    val shareIntent = Intent(Intent.ACTION_SEND)
    shareIntent.putExtra(Intent.EXTRA_STREAM, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        androidx.core.content.FileProvider.getUriForFile(context, context.packageName, outputFile)
    else
        Uri.fromFile(outputFile))
    shareIntent.type = "image/png"
    return shareIntent
}

完全可用的解决方案。在Android 11上进行了测试。 - Navinpd

1
你无法直接分享应用程序内部存储中的uri(当然,应用程序的资源始终在内部存储中)
有两种方法可以实现这一点...
  1. 将图像复制到外部存储器,然后从那里共享它。请参见this

  2. 编写内容提供程序来共享图像。请参考从内部存储创建和共享文件


谢谢你的回答。但是我无法用第一种方法实现它。 - rick
你把图片复制到外部存储了吗? - Arun C
不好意思,我无法复制这张图片。它总是会抛出文件未找到的异常。如果您已经有代码片段,能否请您展示给我看呢? - rick
请确保您的文件名正确,并发布您编写的代码。 - Arun C
让我们在聊天中继续这个讨论 - rick
显示剩余3条评论

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