Frage

Ich möchte eine bestimmte Drawable als die Geräte Tapete setzen, aber alle Tapeten Funktionen akzeptieren Bitmaps nur. Ich kann nicht WallpaperManager benutzen, weil ich bin 2.1 vor.

Auch sind meine Drawables aus dem Internet heruntergeladen und befinden sich nicht in R.drawable.

War es hilfreich?

Lösung 3

Dieser wandelt ein BitmapDrawable auf eine Bitmap.

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

Andere Tipps

Dieses Stück Code hilft.

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

Hier ist eine Version, wo das Bild heruntergeladen wird.

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

Ein Drawable kann auf eine Canvas gezogen werden, und ein Canvas kann durch eine Bitmap gesichert werden:

(Aktualisierte eine schnelle Konvertierung für BitmapDrawables zu handhaben und zu gewährleisten, dass die erzeugte Bitmap eine gültige Größe hat)

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

METHODE 1 : Sie können entweder zu Bitmap wie diese direkt konvertieren

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

METHODE 2 : Sie können sogar die Ressource in die ziehbar konvertieren und aus, dass Sie kann wie folgt erhalten Bitmap

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

API> 22 getDrawable Methode zum ResourcesCompat Klasse bewegt sich also, dass Sie etwas tun, wie dieser

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

sehr einfach

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

So nach einem Blick (und mit) der anderen Antworten, scheint sie alle Umgang mit ColorDrawable und PaintDrawable schlecht. (Vor allem auf Lutschern) schien, dass Shaders wurden so festen Blöcke von Farben gezwickt nicht korrekt behandelt wurden.

Ich verwende den folgenden Code jetzt:

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

Im Gegensatz zu den anderen, wenn Sie setBounds auf dem Drawable rufen, bevor er fragt sie in eine Bitmap zu drehen, wird die Bitmap in der richtigen Größe ziehen!

Vielleicht hilft jemand ...

Von PictureDrawable zu Bitmap, zu verwenden:

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

... implementiert als solche:

Bitmap bmp = pictureDrawableToBitmap((PictureDrawable) drawable);

Hier ist eine bessere Auflösung

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 von Wie ziehbar Bits lesen als Input

Hier ist die schöne Kotlin Version der Antwort von @ Chris.Jenkins bereitgestellt 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

Android stellt eine nicht gerade foward Lösung: BitmapDrawable. Um die Bitmap zu bekommen, werden wir die Ressourcen-ID R.drawable.flower_pic zum einem BitmapDrawable bieten müssen und warf es dann zu einem Bitmap.

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

Mit dieser code.it wird Ihnen helfen, für Ihr Ziel zu erreichen.

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

BitmapFactory.decodeResource() automatisch skaliert das Bitmap, so dass Ihre Bitmap Fuzzy kann sich herausstellen. Um Skalierung zu verhindern, dies zu tun:

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

oder

InputStream is = context.getResources().openRawResource(R.drawable.resource_name)
bitmap = BitmapFactory.decodeStream(is);
 // 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);
        }
    }
}

ImageWorker Bibliothek können kehrt Bitmap ziehbar oder Base64 und umgewandeln.

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

Die Umsetzung

Projektebene Gradle

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

In der Anwendungsebene Gradle

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

Sie können auch speichern und abrufen Bitmaps / Drawables / base64 Bilder von externen.

Überprüfen Sie hier. https://github.com/1AboveAll/ImageWorker/edit/master/README. md

Wenn Sie die Verwendung unter Code Kotlin werden. es wird funktionieren

// für die Verwendung von Bildpfad

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

Android-ktx hat Drawable.toBitmap Methode: https://android.github.io/android-ktx/core-ktx/androidx.graphics.drawable/android.graphics.drawable.-drawable/to-bitmap.html

Von Kotlin

val bitmap = myDrawable.toBitmap()
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top