Java tutorial
//package com.java2s; //License from project: Apache License import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import java.io.InputStream; public class Main { /** * Drawable to Bitmap */ public static Bitmap drawableToBitmap(Drawable drawable) { if (drawable instanceof BitmapDrawable) ((BitmapDrawable) drawable).getBitmap(); int width = drawable.getIntrinsicWidth(); int height = drawable.getIntrinsicHeight(); Bitmap bitmap = createBitmapSafely(width, height, Bitmap.Config.ARGB_8888, 1); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, width, height); drawable.draw(canvas); return bitmap; } public static Bitmap getBitmap(String path) { try { return BitmapFactory.decodeFile(path); } catch (Exception e) { e.printStackTrace(); return null; } } public static Bitmap getBitmap(InputStream is) { try { return BitmapFactory.decodeStream(is); } catch (Exception e) { e.printStackTrace(); return null; } } public static Bitmap createBitmapSafely(int width, int height, Bitmap.Config config, int retryCount) { try { return Bitmap.createBitmap(width, height, config); } catch (OutOfMemoryError e) { e.printStackTrace(); if (retryCount > 0) { System.gc(); return createBitmapSafely(width, height, config, retryCount - 1); } return null; } } }