1042

我想将某个设置Drawable为设备的壁纸,但所有壁纸功能Bitmap都只接受 s。我不能使用WallpaperManager,因为我是 2.1 之前的版本。

此外,我的可绘制对象是从网上下载的,而不是驻留在R.drawable.

4

21 回答 21

1365

这段代码有帮助。

Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
                                           R.drawable.icon_resource);

这是下载图像的版本。

String name = c.getString(str_url);
URL url_value = new URL(name);
ImageView profile = (ImageView)v.findViewById(R.id.vdo_icon);
if (profile != null) {
    Bitmap mIcon1 =
        BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
    profile.setImageBitmap(mIcon1);
}
于 2010-06-14T08:32:47.823 回答
804
public static Bitmap drawableToBitmap (Drawable drawable) {
    Bitmap bitmap = null;

    if (drawable instanceof BitmapDrawable) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        if(bitmapDrawable.getBitmap() != null) {
            return bitmapDrawable.getBitmap();
        }
    }

    if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
        bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
    } else {
        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);
    return bitmap;
}
于 2012-05-15T12:33:19.967 回答
217

这会将 BitmapDrawable 转换为 Bitmap。

Drawable d = ImagesArrayList.get(0);  
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
于 2010-06-14T09:33:55.730 回答
151

ADrawable可以绘制到 a 上Canvas,并且 aCanvas可以由 a 支持Bitmap

(更新以处理BitmapDrawables 的快速转换并确保Bitmap创建的大小有效)

public static Bitmap drawableToBitmap (Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable)drawable).getBitmap();
    }

    int width = drawable.getIntrinsicWidth();
    width = width > 0 ? width : 1;
    int height = drawable.getIntrinsicHeight();
    height = height > 0 ? height : 1;

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap); 
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}
于 2012-02-22T07:35:43.647 回答
58

方法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();
于 2018-02-02T05:22:48.940 回答
40

1)可绘制到位图:

Bitmap mIcon = BitmapFactory.decodeResource(context.getResources(),R.drawable.icon);
// mImageView.setImageBitmap(mIcon);

2)位图到可绘制:

Drawable mDrawable = new BitmapDrawable(getResources(), bitmap);
// mImageView.setDrawable(mDrawable);
于 2019-11-07T07:23:38.977 回答
39

android-ktx 有Drawable.toBitmap方法:https ://android.github.io/android-ktx/core-ktx/androidx.graphics.drawable/android.graphics.drawable.-drawable/to-bitmap.html

来自科特林

val bitmap = myDrawable.toBitmap()
于 2019-06-05T16:41:47.423 回答
32

很简单

Bitmap tempBMP = BitmapFactory.decodeResource(getResources(),R.drawable.image);
于 2013-03-21T18:21:30.080 回答
18

最新的 androidx 核心库 (androidx.core:core-ktx:1.2.0) 现在有一个扩展功能:Drawable.toBitmap(...)将 Drawable 转换为 Bitmap。

于 2020-03-12T05:48:25.107 回答
16

因此,在查看(和使用)其他答案之后,似乎他们都处理ColorDrawablePaintDrawable不好。(特别是在棒棒糖上)似乎对Shaders 进行了调整,因此无法正确处理纯色块。

我现在正在使用以下代码:

public static Bitmap drawableToBitmap(Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    }

    // We ask for the bounds if they have been set as they would be most
    // correct, then we check we are  > 0
    final int width = !drawable.getBounds().isEmpty() ?
            drawable.getBounds().width() : drawable.getIntrinsicWidth();

    final int height = !drawable.getBounds().isEmpty() ?
            drawable.getBounds().height() : drawable.getIntrinsicHeight();

    // Now we check we are > 0
    final Bitmap bitmap = Bitmap.createBitmap(width <= 0 ? 1 : width, height <= 0 ? 1 : height,
            Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

与其他人不同的是,如果您在要求将其转换为位图之前调用setBoundsDrawable,它将以正确的大小绘制位图!

于 2014-12-18T09:54:24.360 回答
13

也许这会帮助某人......

从 PictureDrawable 到 Bitmap,使用:

private Bitmap pictureDrawableToBitmap(PictureDrawable pictureDrawable){ 
    Bitmap bmp = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(), pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888); 
    Canvas canvas = new Canvas(bmp); 
    canvas.drawPicture(pictureDrawable.getPicture()); 
    return bmp; 
}

...这样实施:

Bitmap bmp = pictureDrawableToBitmap((PictureDrawable) drawable);
于 2012-02-08T19:08:03.707 回答
12

这里有更好的分辨率

public static Bitmap drawableToBitmap (Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable)drawable).getBitmap();
    }

    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap); 
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

public static InputStream bitmapToInputStream(Bitmap bitmap) {
    int size = bitmap.getHeight() * bitmap.getRowBytes();
    ByteBuffer buffer = ByteBuffer.allocate(size);
    bitmap.copyPixelsToBuffer(buffer);
    return new ByteArrayInputStream(buffer.array());
}

如何将可绘制位读取为 InputStream 中的代码

于 2013-10-22T11:56:05.840 回答
12

这是@Chris.Jenkins在这里提供的答案的不错的Kotlin版本:https ://stackoverflow.com/a/27543712/1016462

fun Drawable.toBitmap(): Bitmap {
  if (this is BitmapDrawable) {
    return bitmap
  }

  val width = if (bounds.isEmpty) intrinsicWidth else bounds.width()
  val height = if (bounds.isEmpty) intrinsicHeight else bounds.height()

  return Bitmap.createBitmap(width.nonZero(), height.nonZero(), Bitmap.Config.ARGB_8888).also {
    val canvas = Canvas(it)
    setBounds(0, 0, canvas.width, canvas.height)
    draw(canvas)
  }
}

private fun Int.nonZero() = if (this <= 0) 1 else this
于 2017-12-29T21:06:52.207 回答
9

位图位图 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);

这不会每次都起作用,例如,如果您的可绘制对象是可绘制的图层列表,那么它会给出空响应,因此作为替代方案,您需要将可绘制对象绘制到画布中然后保存为位图,请参阅下面的一段代码。

public void drawableToBitMap(Context context, int drawable, int widthPixels, int heightPixels) {
    try {
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/", "drawable.png");
        FileOutputStream fOut = new FileOutputStream(file);
        Drawable drw = ResourcesCompat.getDrawable(context.getResources(), drawable, null);
        if (drw != null) {
            convertToBitmap(drw, widthPixels, heightPixels).compress(Bitmap.CompressFormat.PNG, 100, fOut);
        }
        fOut.flush();
        fOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private Bitmap convertToBitmap(Drawable drawable, int widthPixels, int heightPixels) {
    Bitmap bitmap = Bitmap.createBitmap(widthPixels, heightPixels, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, widthPixels, heightPixels);
    drawable.draw(canvas);
    return bitmap;
}

上面的代码将你在下载目录中的drawable保存为drawable.png

于 2020-06-21T10:10:29.607 回答
8

Android 提供了一个非直接的解决方案:BitmapDrawable. 要获取 Bitmap ,我们必须将资源 id 提供R.drawable.flower_pic给 a BitmapDrawable,然后将其转换为 a Bitmap

Bitmap bm = ((BitmapDrawable) getResources().getDrawable(R.drawable.flower_pic)).getBitmap();
于 2014-05-29T01:39:04.980 回答
5

使用此代码。它将帮助您实现目标。

 Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.profileimage);
    if (bmp!=null) {
        Bitmap bitmap_round=getRoundedShape(bmp);
        if (bitmap_round!=null) {
            profileimage.setImageBitmap(bitmap_round);
        }
    }

  public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
    int targetWidth = 100;
    int targetHeight = 100;
    Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, 
            targetHeight,Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(targetBitmap);
    Path path = new Path();
    path.addCircle(((float) targetWidth - 1) / 2,
            ((float) targetHeight - 1) / 2,
            (Math.min(((float) targetWidth), 
                    ((float) targetHeight)) / 2),
                    Path.Direction.CCW);

    canvas.clipPath(path);
    Bitmap sourceBitmap = scaleBitmapImage;
    canvas.drawBitmap(sourceBitmap, 
            new Rect(0, 0, sourceBitmap.getWidth(),
                    sourceBitmap.getHeight()), 
                    new Rect(0, 0, targetWidth, targetHeight), new Paint(Paint.FILTER_BITMAP_FLAG));
    return targetBitmap;
}
于 2014-05-30T12:13:47.197 回答
5

BitmapFactory.decodeResource()自动缩放位图,因此您的位图可能会变得模糊。要防止缩放,请执行以下操作:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap source = BitmapFactory.decodeResource(context.getResources(),
                                             R.drawable.resource_name, options);

或者

InputStream is = context.getResources().openRawResource(R.drawable.resource_name)
bitmap = BitmapFactory.decodeStream(is);
于 2019-07-09T00:06:19.107 回答
2

ImageWorker 库可以将位图转换为可绘制或 base64,反之亦然。

val bitmap: Bitmap? = ImageWorker.convert().drawableToBitmap(sourceDrawable)

执行

在项目级别 Gradle

allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }

在应用程序级别 Gradle

dependencies {
            implementation 'com.github.1AboveAll:ImageWorker:0.51'
    }

您还可以从外部存储和检索位图/drawables/base64 图像。

在这里检查。https://github.com/1AboveAll/ImageWorker/edit/master/README.md

于 2018-12-09T04:52:58.053 回答
2

如果您使用的是 kotlin,请使用以下代码。它会工作的

// 用于使用图像路径

val image = Drawable.createFromPath(path)
val bitmap = (image as BitmapDrawable).bitmap
于 2019-07-19T08:08:12.343 回答
1
 // get image path from gallery
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
    super.onActivityResult(requestCode, resultcode, intent);

    if (requestCode == 1) {
        if (intent != null && resultcode == RESULT_OK) {             
            Uri selectedImage = intent.getData();

            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            filePath = cursor.getString(columnIndex);

            //display image using BitmapFactory

            cursor.close(); bmp = BitmapFactory.decodeFile(filepath); 
            iv.setBackgroundResource(0);
            iv.setImageBitmap(bmp);
        }
    }
}
于 2012-12-21T04:21:43.610 回答
0

我在这个线程上使用了一些答案,但其中一些没有按预期工作(也许他们在旧版本中工作过)但我想在几次尝试和错误后分享我的,使用扩展功能:

val markerOption = MarkerOptions().apply {
    position(LatLng(driver.lat, driver.lng))
    icon(R.drawabel.your_drawable.toBitmapDescriptor(context))
    snippet(driver.driverId.toString())
}
mMap.addMarker(markerOption)

这是扩展功能:

fun Int.toBitmapDescriptor(context: Context): BitmapDescriptor {
    val vectorDrawable = ResourcesCompat.getDrawable(context.resources, this, context.theme)
    val bitmap = vectorDrawable?.toBitmap(
        vectorDrawable.intrinsicWidth,
        vectorDrawable.intrinsicHeight,
        Bitmap.Config.ARGB_8888
    )
    return BitmapDescriptorFactory.fromBitmap(bitmap!!)
}
于 2022-01-27T01:06:03.017 回答