1042

デバイスの壁紙として特定のものを設定したいのですDrawableが、すべての壁紙機能はBitmapsのみを受け入れます。WallpaperManager2.1より前なので使用できません。

また、私のドローアブルはWebからダウンロードされ、に存在しません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がビットマップに変換されます。

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

ADrawableは、に描画できCanvas、 aは:Canvasでバックアップできます。Bitmap

(sのクイック変換を処理し、作成されたサイズが有効BitmapDrawableであることを確認するために更新されました)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へのビットマップ:

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

Kotlinから

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をビットマップに変換する拡張機能Drawable.toBitmap(...)が追加されました。

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

setBounds他とは異なり、ビットマップに変換するように要求する前にを呼び出すとDrawable、ビットマップが正しいサイズで描画されます。

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

これは毎回機能するとは限りません。たとえば、ドローアブルがレイヤーリストドローアブルの場合はnull応答が返されるため、代わりにドローアブルをキャンバスに描画してビットマップとして保存する必要があります。以下のコードを参照してください。

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.pngとして描画可能であることを保存します

于 2020-06-21T10:10:29.607 に答える
8

Androidは、まっすぐではないフォワードソリューションを提供しますBitmapDrawable。ビットマップを取得するには、リソースIDR.drawable.flower_picをに提供してBitmapDrawableから、にキャストする必要があり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'
    }

外部からビットマップ/ドローアブル/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 に答える