Hoe converteer je een Drawable naar een Bitmap?

Ik wil een bepaalde Drawableals achtergrond van het apparaat instellen, maar alle achtergrondfuncties accepteren alleen Bitmaps. Ik kan WallpaperManagerniet gebruiken omdat ik ouder ben dan 2.1.

Mijn tekenfilms worden ook gedownload van internet en staan niet in R.drawable.


Antwoord 1, autoriteit 100%

Dit stukje code helpt.

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

Hier een versie waarin de afbeelding wordt gedownload.

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

Antwoord 2, autoriteit 59%

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

Antwoord 3, autoriteit 16%

Dit converteert een BitmapDrawable naar een Bitmap.

Drawable d = ImagesArrayList.get(0);  
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();

Antwoord 4, autoriteit 11%

Een Drawablekan op een Canvasworden getekend, en een Canvaskan worden ondersteund door een Bitmap:

(Bijgewerkt om een snelle conversie voor BitmapDrawables af te handelen en om ervoor te zorgen dat de gemaakte Bitmapeen geldige grootte heeft)

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

Antwoord 5, autoriteit 4%

METHODE 1: Ofwel kunt u direct converteren naar een bitmap op deze manier

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

METHODE 2: je kunt de bron zelfs converteren naar de tekenbare en daaruit kun je een bitmap krijgen zoals deze

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

Voor API & GT; 22 getDrawableMETHODE VERHUURD NAAR DE ResourcesCompatCLASSE ZO WANNEER JE DOE DOE DOETS MET IETS

Bitmap myLogo = ((BitmapDrawable) ResourcesCompat.getDrawable(context.getResources(), R.drawable.logo, null)).getBitmap();

6, Autoriteit 3%

1) Onderwerp op bitmap:

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

2) Bitmap tot opleiding:

Drawable mDrawable = new BitmapDrawable(getResources(), bitmap);
// mImageView.setDrawable(mDrawable);

7, Autoriteit 3%

Android-KTX heeft Drawable.toBitmapMETHODE: https://android.github.io/android-ktx/core-ktx/androidx.graphics.drowable/android.graphics.DRAAWBARE.- Tekenbaar / to-bitmap.html

van kotlin

val bitmap = myDrawable.toBitmap()

8, Autoriteit 2%

Zeer eenvoudig

Bitmap tempBMP = BitmapFactory.decodeResource(getResources(),R.drawable.image);

9

Misschien helpt dit iemand …

Vanaf afgebeelde bitmap, gebruik:

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

… als zodanig geïmplementeerd:

Bitmap bmp = pictureDrawableToBitmap((PictureDrawable) drawable);

Antwoord 10

De nieuwste Android-kernbibliotheek (androidx.core:core-ktx:1.2.0) heeft nu een extensiefunctie: Drawable.toBitmap(...)om een Drawable naar een Bitmap te converteren.


Antwoord 11

Hier is een betere resolutie

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

Code van Hoe tekenbare bits te lezen als InputStream


Antwoord 12

Hier is de mooie Kotlin-versie van het antwoord van @Chris.Jenkins hier: 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

Antwoord 13

Android biedt een niet-rechttoe rechtaan oplossing: BitmapDrawable. Om de Bitmap te krijgen, moeten we de resource-id R.drawable.flower_picaan de a BitmapDrawablegeven en deze vervolgens casten naar een Bitmap.

Bitmap bm = ((BitmapDrawable) getResources().getDrawable(R.drawable.flower_pic)).getBitmap();

Antwoord 14

Gebruik deze code.it zal je helpen om je doel te bereiken.

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

Antwoord 15

BitmapFactory.decodeResource()schaalt de bitmap automatisch, zodat uw bitmap wazig kan worden. Ga als volgt te werk om schaalvergroting te voorkomen:

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

of

InputStream is = context.getResources().openRawResource(R.drawable.resource_name)
bitmap = BitmapFactory.decodeStream(is);

Antwoord 16

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

Dit zal niet elke keer werken, bijvoorbeeld als uw tekenbare tekenbare lagenlijst tekenbaar is, dan geeft het een null-antwoord, dus als alternatief moet u uw tekenbaar teken in canvas tekenen en vervolgens opslaan als bitmap, zie hieronder een kopje code.

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

bovenstaande code sla je op als drawable.png in de downloadmap


Antwoord 17

ImageWorker Library kan bitmap converteren naar tekenbaar of base64 en vice versa.

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

Implementatie

In projectniveau Gradle

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

In applicatieniveau Gradle

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

Je kunt ook externe bitmaps/drawables/base64-afbeeldingen opslaan en ophalen.

Kijk hier. https://github.com/1AboveAll/ImageWorker/edit/master/README. md


Antwoord 18

Als je kotlin gebruikt, gebruik dan onderstaande code. het zal werken

// voor het gebruik van afbeeldingspad

val image = Drawable.createFromPath(path)
val bitmap = (image as BitmapDrawable).bitmap

Antwoord 19

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

Other episodes