如何将资源中的Drawable图像转换为Bitmap

32
我正在尝试将Drawable中的图片附加到电子邮件中(从我的应用程序发送到Gmail应用程序)。
我尝试了下面的代码:
        Intent emailintent2 = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
        emailintent2.setType("image/*");
        emailintent2.putExtra(Intent.EXTRA_EMAIL, emailaddress2);
        emailintent2.putExtra(Intent.EXTRA_SUBJECT, CorAsunto);
        emailintent2.putExtra(Intent.EXTRA_TEXT, message2);

        ArrayList<Uri> uris = new ArrayList<Uri>();
        uris.add(Uri.parse("android.resource://" + getPackageName() + "/" + R.drawable.image1));
        uris.add(Uri.parse("android.resource://" + getPackageName() + "/" + R.drawable.image2));

        emailintent2.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
        startActivity(emailintent2);

但是当我将图片附加到电子邮件时,我得到的附件没有扩展名“ .png”,这是一个大问题。
因此,我想尝试将这些Drawable图像转换为Bitmap,并且我认为ArrayList将不得不是Bitmap。我认为我会得到图像作为附件中定义的图像。
如果可能的话,有人能告诉我如何做吗?转换为位图,添加到ArrayList并附加图像。
如果我说的一切都错了,有人能给我一个解决方案吗?我需要将来自Drawable的图像作为(.png)扩展名附加到电子邮件中。

你试过 getBitmap() 吗? - hakkikonu
1
将您的标题复制并粘贴到谷歌中:https://dev59.com/T2oy5IYBdhLWcg3wL7L1 - dymmeh
http://codingaffairs.blogspot.com/2016/06/how-to-convert-drawable-to-bitmap-in.html - Developine
请查看 https://dev59.com/T2oy5IYBdhLWcg3wL7L1#14839494 获取最新的API。 - AndyW
9个回答

59

有3种执行转换的方法:

  1. 使用资源图片设置ImageView

  2. imageView.setImageResource(R.drawable.icon);
    

    然后从imageView获取位图

    Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
    
  3. 通过资源 ID直接获取可绘制资源

  4. Bitmap icon = BitmapFactory.decodeResource(getResources(),R.drawable.profile_circle);
    
  5. 将图像设置到 ImageView 上,然后将其转换为 Bitmap(适用于 SVG/VectorDrawable)

  6. ImageView imgView = (ImageView) findViewById(R.id.ImageView);
    imgView.setImageResource(R.drawable.abc_image);
    z.setDrawingCacheEnabled(true);
    Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
    

35
Drawable myDrawable = getResources().getDrawable(R.drawable.anImage);
Bitmap anImage      = ((BitmapDrawable) myDrawable).getBitmap();

也可以在XML文件中使用<bitmap>元素来定义。

2023年的计划

距离我第一次回答已经过去了10年:

Drawable drawable = ContextCompat.getDrawable(context, R.drawable.your_drawable);

if (drawable instanceof BitmapDrawable) {
    // If your drawable is already a BitmapDrawable, you can get the bitmap directly
    Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
} else if (drawable instanceof VectorDrawable || drawable instanceof GradientDrawable) {
    // If it's another type of drawable (like VectorDrawable), you need to create a bitmap and draw the drawable onto it
    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                                        drawable.getIntrinsicHeight(),
                                        Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
}

http://codingaffairs.blogspot.com/2016/06/how-to-convert-drawable-to-bitmap-in.html - Developine
这应该比其他解决方案更有效率,但我看到getDrawable已经被弃用了。 - M. Usman Khan
3
无法正常运行,出现“ClassCastException: android.graphics.drawable.ColorDrawable cannot be cast to android.graphics.drawable.BitmapDrawable”错误。 - Pochmurnik

10

这是一段代码,请查看:

Bitmap Icon = BitmapFactory.decodeResource(getResources(), R.drawable.large_icon);

6
直接的方法是:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);

你可以在.xml文件中定义位图,以便更好地进行配置,方法如下:

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@[package:]drawable/drawable_resource"
    android:antialias=["true" | "false"]
    android:dither=["true" | "false"]
    android:filter=["true" | "false"]
    android:gravity=["top" | "bottom" | "left" | "right" | "center_vertical" |
                      "fill_vertical" | "center_horizontal" | "fill_horizontal" |
                      "center" | "fill" | "clip_vertical" | "clip_horizontal"]
    android:mipMap=["true" | "false"]
    android:tileMode=["disabled" | "clamp" | "repeat" | "mirror"] />

6
Bitmap icon = BitmapFactory.decodeResource(mContext.getResources(),
            R.drawable.ic_launcher);

其中mContext是您的活动上下文。


2
public Bitmap convertToBitmap(Drawable drawable, int widthPixels, int heightPixels) {
    Bitmap mutableBitmap = Bitmap.createBitmap(widthPixels, heightPixels, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(mutableBitmap);
    drawable.setBounds(0, 0, widthPixels, heightPixels);
    drawable.draw(canvas);

    return mutableBitmap;
}

https://msol.io/blog/android/android-convert-drawable-to-bitmap/的最初回答对我有用。


1
谢谢。这个方法允许从矢量图中获取位图,而其他方法只能从位图中获取。 - Andrey

1
    public Bitmap getBitmap(@DrawableRes final int resId) {
        Drawable drawable = getResources().getDrawable(resId);;
        Canvas canvas = new Canvas();
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(),
                Bitmap.Config.ARGB_8888);
        canvas.setBitmap(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

当你发布代码时,添加一些评论通常是有帮助的。 - Bink

1

方法1:你可以直接像这样转换为位图

 Bitmap myLogo = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_drawable);

方法2:您甚至可以将资源转换为可绘制对象,然后从中获取位图,如下所示

Bitmap myLogo = ((BitmapDrawable)getResources().getDrawable(R.drawable.logo)).getBitmap();

对于API > 22,getDrawable方法已经移动到ResourcesCompat类中,因此你需要像这样做:
Bitmap myLogo = ((BitmapDrawable) ResourcesCompat.getDrawable(context.getResources(), R.drawable.logo, null)).getBitmap();

-1

就这么简单

val bitmap = BitmapFactory.decodeResource(resources, R.drawable.some_image)

我在矢量图像中得到了 null,但png图像资源运行正常。


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