Bitmap以最省內存的方式獲取本地資源,轉換drawable到bitmap

public final class BitmapUtils {

    /**
     * 清空ImageView中的圖片的內存
     */
    public static void clearImageMemory(View view) {
        if (view != null && view instanceof ImageView) {
            Drawable d = ((ImageView)view).getDrawable();
            if (d != null && d instanceof BitmapDrawable) {
                Bitmap bmp = ((BitmapDrawable)d).getBitmap();
                bmp.recycle();
                System.gc();
            }
            ((ImageView)view).setImageDrawable(null);
            if (d != null) {
                d.setCallback(null);
            }
        }
    }

    /**
     * 以最省內存的方式讀取本地資源的圖片
     *
     * @param context Context
     * @param resId   圖片資源ID
     * @return Bitmap
     */
    @SuppressWarnings("deprecation")
    public static Bitmap readBitmap(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        // 獲取資源圖片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    /**
     * 轉換DrawableBitmap
     *
     * @param drawable Drawable
     * @return 轉換DrawableBitmap
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable != null && drawable instanceof BitmapDrawable) {
            BitmapDrawable bd = (BitmapDrawable)drawable;
            return bd.getBitmap();
        }
        return null;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章