如何使用"共享图像使用"共享Intent在android中共享图像?

Abh*_*eet 71 android share uri image

我在该应用程序中有图像厨房应用程序我将所有图像放入drawable-hdpi文件夹中.我在我的活动中调用了这样的图像:

private Integer[] imageIDs = {
        R.drawable.wall1, R.drawable.wall2,
        R.drawable.wall3, R.drawable.wall4,
        R.drawable.wall5, R.drawable.wall6,
        R.drawable.wall7, R.drawable.wall8,
        R.drawable.wall9, R.drawable.wall10
};
Run Code Online (Sandbox Code Playgroud)

所以现在我想知道我如何使用共享Intent我分享这些图像我推出的共享代码如下:

     Button shareButton = (Button) findViewById(R.id.share_button);
     shareButton.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {

        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        Uri screenshotUri = Uri.parse(Images.Media.EXTERNAL_CONTENT_URI + "/" + imageIDs);

        sharingIntent.setType("image/jpeg");
        sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
        startActivity(Intent.createChooser(sharingIntent, "Share image using"));  

         }
    });
Run Code Online (Sandbox Code Playgroud)

当我点击分享按钮时我也有共享按钮分享框正在打开但当我克服任何服务时,大多数崩溃或一些服务说:无法打开图像所以我怎么能解决这个问题或者是否有任何其他格式代码来共享图像????

编辑:

我尝试使用下面的代码.但它不起作用.

Button shareButton = (Button) findViewById(R.id.share_button);
     shareButton.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {

        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        Uri screenshotUri = Uri.parse("android.resource://com.android.test/*");
        try {
            InputStream stream = getContentResolver().openInputStream(screenshotUri);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        sharingIntent.setType("image/jpeg");
        sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
        startActivity(Intent.createChooser(sharingIntent, "Share image using"));  

         }
    });
Run Code Online (Sandbox Code Playgroud)

如果不介意有人plz更正我的上述代码或给我一个正确的例子PLZ我如何从drawable-hdpi文件夹共享我的图像

sup*_*erM 110

Bitmap icon = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.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/temporary_file.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));
Run Code Online (Sandbox Code Playgroud)

  • 是的,如果您使用createTempFile,则会在您的应用专用的目录中创建该文件.因此,其他应用程序(即您与之共享的应用程序)将无法检索图像. (13认同)
  • 您还应该关闭输出流. (7认同)
  • 1.)不要忘记关闭FileOutputStream.2.)不要硬编码"/ sdcard /"; 请改用Environment.getExternalStorageDirectory().getPath() (7认同)
  • 是否有理由反对使用`File f = File.createTempFile("sharedImage",suffix,getExternalCacheDir());`,并使用`share.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(f));`? (3认同)
  • @superM可以帮助我如何从drawable文件夹中分享 (2认同)

Seb*_*jas 38

superM提出的解决方案已经为我工作了很长时间,但最近我在4.2(HTC One)上测试了它并且它在那里停止工作.我知道这是一种解决方法,但它是唯一一款适用于所有设备和版本的解决方案.

根据文档,开发人员被要求"使用系统MediaStore"来发送二进制内容.但是,这具有(不)优势,即媒体内容将永久保存在设备上.

如果这是您的选项,您可能希望授予权限WRITE_EXTERNAL_STORAGE并使用系统范围的MediaStore.

Bitmap icon = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");

ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,
        values);


OutputStream outstream;
try {
    outstream = getContentResolver().openOutputStream(uri);
    icon.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
    outstream.close();
} catch (Exception e) {
    System.err.println(e.toString());
}

share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Image"));
Run Code Online (Sandbox Code Playgroud)

  • 这会创建一个新图像.如何删除新图像? (9认同)
  • 这是我在Facebook上分享的唯一解决方案!谢谢. (3认同)
  • @BlueMango你找到了解决方案吗? (2认同)

Hem*_*ori 21

首先添加权限

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

使用res的位图

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"));
Run Code Online (Sandbox Code Playgroud)

通过蓝牙和其他信使测试

奇迹般有效.


Kuk*_*won 17

我发现最简单的方法是使用MediaStore临时存储您要共享的图像:

Drawable mDrawable = mImageView.getDrawable();
Bitmap mBitmap = ((BitmapDrawable) mDrawable).getBitmap();

String path = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "Image Description", null);
Uri uri = Uri.parse(path);

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share Image"));
Run Code Online (Sandbox Code Playgroud)

来自:与意图共享内容

  • 不要忘记在 manifest.xml 中添加 ermission: &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; (2认同)

小智 12

谢谢大家,我尝试了给出的几个选项,但这些选项似乎不适用于最新的 android 版本,因此添加适用于最新 android 版本的修改步骤。这些基于上面的几个答案,但经过修改,解决方案基于文件提供程序的使用:

步骤1

在清单文件中添加以下代码:

<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/file_provider_paths" />
</provider>
Run Code Online (Sandbox Code Playgroud)

步骤:2 在res > xml中创建XML文件

在 xml 中创建 file_provider_paths 文件。

请注意,这是我们在上一步中包含在 android:resource 中的文件。

在file_provider_paths中写入以下代码:

<?xml version="1.0" encoding="utf-8"?>
<paths>
        <cache-path name="cache" path="/" />
        <files-path name="files" path="/" />
</paths>
Run Code Online (Sandbox Code Playgroud)

步骤:3

之后转到您的按钮单击:

Button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

       Bitmap bit = BitmapFactory.decodeResource(context.getResources(),  R.drawable.filename);
        File filesDir = context.getApplicationContext().getFilesDir();
        File imageFile = new File(filesDir, "birds.png");
        OutputStream os;
        try {
            os = new FileOutputStream(imageFile);
            bit.compress(Bitmap.CompressFormat.PNG, 100, os); 
            os.flush();
            os.close();
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
        }

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        Uri imageUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, imageFile);

        intent.putExtra(Intent.EXTRA_STREAM, imageUri);
        intent.setType("image/*");
        context.startActivity(intent);
    }
});
Run Code Online (Sandbox Code Playgroud)

有关更详细的说明,请访问 https://droidlytics.wordpress.com/2020/08/04/use-fileprovider-to-share-image-from-recyclerview/


SAN*_*PTA 11

最简单,最简单的代码,您可以使用它来共享图库中的图像.

 String image_path;
            File file = new File(image_path);
            Uri uri = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent .setType("image/*");
            intent .putExtra(Intent.EXTRA_STREAM, uri);
            context.startActivity(intent );
Run Code Online (Sandbox Code Playgroud)


Naj*_*Ali 11

如何在机器上以progamatically方式共享图像,有时您想拍摄视图的快照然后分享它,请按照以下步骤操作:1.添加对mainfest文件的权限

<uses-permission    
   android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Run Code Online (Sandbox Code Playgroud)

2.Very首先拍摄视图的截图,例如Imageview,Textview,Framelayout,LinearLayout等

例如,您有一个图像视图来截取调用此方法在oncreate()

 ImageView image= (ImageView)findViewById(R.id.iv_answer_circle);
     ///take a creenshot
    screenShot(image);
Run Code Online (Sandbox Code Playgroud)


点击按钮或您想要的位置拍摄屏幕截图呼叫共享图像方法之后

shareBitmap(screenShot(image),"myimage");
Run Code Online (Sandbox Code Playgroud)

在create方法之后定义这两个方法##

    public Bitmap screenShot(View view) {
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
            view.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);
    return bitmap;
}

//////// this method share your image
private void shareBitmap (Bitmap bitmap,String fileName) {
    try {
        File file = new File(getContext().getCacheDir(), fileName + ".png");
        FileOutputStream fOut = new FileOutputStream(file);
        bitmap.compress(CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
        file.setReadable(true, false);
        final Intent intent = new Intent(     android.content.Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        intent.setType("image/png");
        startActivity(intent);
    } catch (Exception e) {
        e.printStackTrace();
    }

}
Run Code Online (Sandbox Code Playgroud)


wir*_*d00 10

这是一个适合我的解决方案.一个问题是你需要将图像存储在共享或非应用程序的私有位置(http://developer.android.com/guide/topics/data/data-storage.html#InternalCache)

许多建议说要存储在Apps"私有"缓存位置,但这当然不能通过其他外部应用程序访问,包括正在使用的通用共享文件意图.当你尝试这个时,它会运行,但是例如dropbox会告诉你文件不再可用.

/*步骤1 - 使用下面的文件保存功能在本地保存位图文件.*/

localAbsoluteFilePath = saveImageLocally(bitmapImage);
Run Code Online (Sandbox Code Playgroud)

/*步骤2 - 将非私有绝对文件路径共享到共享文件意图*/

if (localAbsoluteFilePath!=null && localAbsoluteFilePath!="") {

    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    Uri phototUri = Uri.parse(localAbsoluteFilePath);

    File file = new File(phototUri.getPath());

    Log.d(TAG, "file path: " +file.getPath());

    if(file.exists()) {
        // file create success

    } else {
        // file create fail
    }
    shareIntent.setData(phototUri);
    shareIntent.setType("image/png");
    shareIntent.putExtra(Intent.EXTRA_STREAM, phototUri);
    activity.startActivityForResult(Intent.createChooser(shareIntent, "Share Via"), Navigator.REQUEST_SHARE_ACTION);
}   
Run Code Online (Sandbox Code Playgroud)

/*保存图像功能*/

    private String saveImageLocally(Bitmap _bitmap) {

        File outputDir = Utils.getAlbumStorageDir(Environment.DIRECTORY_DOWNLOADS);
        File outputFile = null;
        try {
            outputFile = File.createTempFile("tmp", ".png", outputDir);
        } catch (IOException e1) {
            // handle exception
        }

        try {
            FileOutputStream out = new FileOutputStream(outputFile);
            _bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.close();

        } catch (Exception e) {
            // handle exception
        }

        return outputFile.getAbsolutePath();
    }
Run Code Online (Sandbox Code Playgroud)

/*步骤3 - 处理共享文件意图结果.需要远程临时文件等*/

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

            // deal with this with whatever constant you use. i have a navigator object to handle my navigation so it also holds all mys constants for intents
        if (requestCode== Navigator.REQUEST_SHARE_ACTION) {
            // delete temp file
            File file = new File (localAbsoluteFilePath);
            file.delete();

            Toaster toast = new Toaster(activity);
            toast.popBurntToast("Successfully shared");
        }


    }   
Run Code Online (Sandbox Code Playgroud)

我希望能有所帮助.

  • 修复,我实际上并没有使用log.d,我有一个包装函数.当我改变示例以适合SO时,我必须写错字.干杯 (2认同)

小智 7

我厌倦了搜索从我的应用程序到其他应用程序共享视图或图像的不同选项.最后我得到了解决方案.

第1步:共享意图处理阻止.这将弹出您的窗口,其中包含您手机中的应用程序列表

public void share_bitMap_to_Apps() {

    Intent i = new Intent(Intent.ACTION_SEND);

    i.setType("image/*");
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    /*compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] bytes = stream.toByteArray();*/


    i.putExtra(Intent.EXTRA_STREAM, getImageUri(mContext, getBitmapFromView(relative_me_other)));
    try {
        startActivity(Intent.createChooser(i, "My Profile ..."));
    } catch (android.content.ActivityNotFoundException ex) {

        ex.printStackTrace();
    }


}
Run Code Online (Sandbox Code Playgroud)

第2步:将视图转换为BItmap

public static Bitmap getBitmapFromView(View view) {
    //Define a bitmap with the same size as the view
    Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(),      view.getHeight(), Bitmap.Config.ARGB_8888);
    //Bind a canvas to it
    Canvas canvas = new Canvas(returnedBitmap);
    //Get the view's background
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        //has background drawable, then draw it on the canvas
        bgDrawable.draw(canvas);
    else
        //does not have background drawable, then draw white background on the canvas
        canvas.drawColor(Color.WHITE);
    // draw the view on the canvas
    view.draw(canvas);
    //return the bitmap
    return returnedBitmap;
}
Run Code Online (Sandbox Code Playgroud)

第3步:

从位图图像获取URI

public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}
Run Code Online (Sandbox Code Playgroud)