通过Android Intent共享位图

通过Android Intent共享位图,android,android-intent,bitmap,intentfilter,Android,Android Intent,Bitmap,Intentfilter,在我的android应用程序中,我有一个位图(比如b)和一个按钮。现在,当我点击按钮,我想分享位图。我正在使用我的onClick()中的以下代码来实现这一点:- Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("image/png"); intent.putExtra(Intent.EXTRA_STREAM, b); startActivity(Intent.createChooser(intent , "Share"

在我的android应用程序中,我有一个位图(比如b)和一个按钮。现在,当我点击按钮,我想分享位图。我正在使用我的
onClick()
中的以下代码来实现这一点:-

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/png");
intent.putExtra(Intent.EXTRA_STREAM, b);
startActivity(Intent.createChooser(intent , "Share"));
我期待所有能够处理这个意图的应用程序的列表,但我什么也没有得到。android studio中没有应用程序列表,也没有任何错误。我的申请被挂了一段时间,然后就退出了

我已经检查了位图,它很好(它不是空的)

我哪里出错了?

引用:

内容:一个URI,包含与意图相关联的数据流,与操作_SEND一起使用,以提供正在发送的数据


因此,
b
不应该是
位图
,而是指向
位图
Uri
,由
内容提供者提供服务。例如,您可以将
位图
写入一个文件,然后使用
文件提供程序
为其提供服务。

正如Commonware所述,您需要获取位图的URI,并将其作为额外的URI传递

String bitmapPath = Images.Media.insertImage(getContentResolver(), bitmap,"title", null);
Uri bitmapUri = Uri.parse(bitmapPath);
...
intent.putExtra(Intent.EXTRA_STREAM, bitmapUri );

**我终于找到了解决办法。**

第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();
    }


}
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);
}
第二步: 将视图转换为位图

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;
}
ImageView imageView = findViewById(R.id.image);
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();

//save the image now:
saveImage(bitmap);
//share it
send();
第三步:

private static void saveImage(Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().getAbsolutePath();
    File myDir = new File(root + "/saved_images");
    Log.i("Directory", "==" + myDir);
    myDir.mkdirs();

    String fname = "Image-test" + ".jpg";
    File file = new File(myDir, fname);
    if (file.exists()) file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
public void send() {
    try {
        File myFile = new File("/storage/emulated/0/saved_images/Image-test.jpg");
        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();
    }
}
从位图图像获取URI

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();
    }


}
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);
}

我发现了该解决方案的两种变体。两者都涉及将位图保存到存储器,但图像不会显示在库中

第一种变体: 保存到外部存储器

  • 但要转到应用程序的私人文件夹

  • 对于API,在花费大量时间之后:

    检查是否已授予权限。然后:

    private static void saveImage(Bitmap finalBitmap) {
    
        String root = Environment.getExternalStorageDirectory().getAbsolutePath();
        File myDir = new File(root + "/saved_images");
        Log.i("Directory", "==" + myDir);
        myDir.mkdirs();
    
        String fname = "Image-test" + ".jpg";
        File file = new File(myDir, fname);
        if (file.exists()) file.delete();
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void send() {
        try {
            File myFile = new File("/storage/emulated/0/saved_images/Image-test.jpg");
            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();
        }
    }
    
    步骤1:创建要在活动中显示的图像的ImageView,然后将其转换为无位图

    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;
    }
    
    ImageView imageView = findViewById(R.id.image);
    Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
    
    //save the image now:
    saveImage(bitmap);
    //share it
    send();
    
    步骤2:将图像存储在内部文件夹中:

    private static void saveImage(Bitmap finalBitmap) {
    
        String root = Environment.getExternalStorageDirectory().getAbsolutePath();
        File myDir = new File(root + "/saved_images");
        Log.i("Directory", "==" + myDir);
        myDir.mkdirs();
    
        String fname = "Image-test" + ".jpg";
        File file = new File(myDir, fname);
        if (file.exists()) file.delete();
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void send() {
        try {
            File myFile = new File("/storage/emulated/0/saved_images/Image-test.jpg");
            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();
        }
    }
    
    步骤3:发送保存的图像:

    private static void saveImage(Bitmap finalBitmap) {
    
        String root = Environment.getExternalStorageDirectory().getAbsolutePath();
        File myDir = new File(root + "/saved_images");
        Log.i("Directory", "==" + myDir);
        myDir.mkdirs();
    
        String fname = "Image-test" + ".jpg";
        File file = new File(myDir, fname);
        if (file.exists()) file.delete();
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void send() {
        try {
            File myFile = new File("/storage/emulated/0/saved_images/Image-test.jpg");
            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();
        }
    }
    

    现在,在发送后,如果不想将保存的图像保存在存储器中,您可以删除该图像。检查其他链接以执行此操作。

    Kotlin中的解决方案在图像文件名中带有时间戳:

    private void sharePalette(Bitmap bitmap) {
    
     String bitmapPath = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "palette", "share palette");
        Uri bitmapUri = Uri.parse(bitmapPath);
    
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/png");
        intent.putExtra(Intent.EXTRA_STREAM, bitmapUri);
        startActivity(Intent.createChooser(intent, "Share"));
    }
    
    val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
    val imagePath = MediaStore.Images.Media.insertImage(
        context?.contentResolver,
        bitmap,
        "img_$timeStamp",
        null
    )
    val shareIntent = Intent(Intent.ACTION_SEND).apply {
        type = "image/*"
        putExtra(Intent.EXTRA_STREAM, Uri.parse(imagePath))
    }
    context?.startActivity(Intent.createChooser(shareIntent, null))
    

    别忘了要求android.permission.WRITE_EXTERNAL_storage没有写外部存储的解决方案吗?添加一些描述以回答清楚的理解@lalit BaghelIt工作,但也存储图像。所以,这一形象在《勇敢》中也有所体现。我怎样才能避免保存图像或将其显示到gallary中。@JaydipKalkani我也需要这个,但也许我们不能。我认为这可能是最好的解决方案,一步一步详细解释。如果出于安全考虑,与缓存中存储的图像共享会更好。我错过了添加xml和provider的一步,所以它不起作用,但最终按照这些步骤进行操作,它现在可以工作了。通过internet通过电子邮件共享的最佳解决方案。自Android X以来,文件提供商的新包名为:
    androidx.core.content.FileProvider