首页 文章

如何将Drawable转换为位图?

提问于
浏览
832

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

此外,我的drawables是从网上下载的,不在 R.drawable 中 .

15 回答

  • 129

    使用此代码:

    Bitmap bitmap= BitmapFactory.decodeResource(context.getResources(), 
        R.drawable.icon_name);
    
  • 9
    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;
    }
    
  • 6

    这段代码有帮助 .

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

    Drawable 可以绘制到 Canvas 上, Canvas 可以由 Bitmap 支持:

    (已更新以处理 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;
    }
    
  • 7

    这是更好的分辨率

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

    代码来自How to read drawable bits as InputStream

  • 31

    这是@ 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
    
  • 71
    // 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);
            }
        }
    }
    
  • 671

    这会将BitmapDrawable转换为Bitmap .

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

    METHOD 1 :您可以直接转换为这样的位图

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

    METHOD 2 :您甚至可以将资源转换为drawable,从中可以获得这样的位图

    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();
    
  • 4

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

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

    ImageWorker Library可以将位图转换为drawable或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

  • 201

    非常简单

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

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

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

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

    从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);
    
  • 10

    所以在查看(和使用)其他答案之后,似乎他们都严重处理 ColorDrawablePaintDrawable . (特别是在棒棒糖上)似乎调整了 Shader s,因此没有正确处理固体颜色块 .

    我现在使用以下代码:

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

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

相关问题