Example usage for android.graphics BitmapFactory decodeResource

List of usage examples for android.graphics BitmapFactory decodeResource

Introduction

In this page you can find the example usage for android.graphics BitmapFactory decodeResource.

Prototype

public static Bitmap decodeResource(Resources res, int id, Options opts) 

Source Link

Document

Synonym for opening the given resource and calling #decodeResourceStream .

Usage

From source file:com.aniruddhc.acemusic.player.NowPlayingQueueActivity.NowPlayingQueueActivity.java

public Bitmap decodeSampledBitmapFromResource(int resID, int reqWidth, int reqHeight) {

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;/*from   w ww .java  2  s .  c o  m*/
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;
    options.inPurgeable = true;

    return BitmapFactory.decodeResource(getBaseContext().getResources(), resID, options);
}

From source file:com.github.chenxiaolong.dualbootpatcher.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.drawer_layout);

    mHandler = new Handler();

    mPrefs = getSharedPreferences("settings", 0);

    if (savedInstanceState != null) {
        mTitle = savedInstanceState.getInt(EXTRA_TITLE);
    }/*from w  w  w .  j a v a  2 s  .c  o  m*/

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open,
            R.string.drawer_close) {
        @Override
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);

            if (mPending != null) {
                mHandler.post(mPending);
                mPending = null;
            }
        }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
    }

    mDrawerView = (NavigationView) findViewById(R.id.left_drawer);
    mDrawerView.setNavigationItemSelectedListener(this);

    // There's a weird performance issue when the drawer is first opened, no matter if we set
    // the background on the nav header RelativeLayout, set the image on an ImageView, or use
    // Picasso to do either asynchronously. By accident, I noticed that using Picasso's resize()
    // method with any dimensions (even the original) works around the performance issue. Maybe
    // something doesn't like PNGs exported from GIMP?
    View header = mDrawerView.inflateHeaderView(R.layout.nav_header);
    ImageView navImage = (ImageView) header.findViewById(R.id.nav_header_image);
    BitmapFactory.Options dimensions = new BitmapFactory.Options();
    dimensions.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(getResources(), R.drawable.material, dimensions);
    Picasso.with(this).load(R.drawable.material).resize(dimensions.outWidth, dimensions.outHeight)
            .into(navImage);

    // Set nav drawer header text
    TextView appName = (TextView) header.findViewById(R.id.nav_header_app_name);
    appName.setText(BuildConfig.APP_NAME_RESOURCE);
    TextView appVersion = (TextView) header.findViewById(R.id.nav_header_app_version);
    appVersion.setText(String.format(getString(R.string.version), BuildConfig.VERSION_NAME));

    // Nav drawer width according to material design guidelines
    // http://www.google.com/design/spec/patterns/navigation-drawer.html
    // https://medium.com/sebs-top-tips/material-navigation-drawer-sizing-558aea1ad266
    final Display display = getWindowManager().getDefaultDisplay();
    final Point size = new Point();
    display.getSize(size);

    final ViewGroup.LayoutParams params = mDrawerView.getLayoutParams();
    int toolbarHeight = getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material);
    params.width = Math.min(size.x - toolbarHeight, 6 * toolbarHeight);
    mDrawerView.setLayoutParams(params);

    if (savedInstanceState != null) {
        mFragment = savedInstanceState.getInt(EXTRA_FRAGMENT);

        showFragment();

        mDrawerItemSelected = savedInstanceState.getInt(EXTRA_SELECTED_ITEM);
    } else {
        String[] initialScreens = getResources().getStringArray(R.array.initial_screen_entry_values);
        String initialScreen = mPrefs.getString("initial_screen", null);
        if (initialScreen == null || !ArrayUtils.contains(initialScreens, initialScreen)) {
            initialScreen = INITIAL_SCREEN_ABOUT;
            Editor e = mPrefs.edit();
            e.putString("initial_screen", initialScreen);
            e.apply();
        }

        int navId;
        switch (initialScreen) {
        case INITIAL_SCREEN_ABOUT:
            navId = R.id.nav_about;
            break;
        case INITIAL_SCREEN_ROMS:
            navId = R.id.nav_roms;
            break;
        case INITIAL_SCREEN_PATCHER:
            navId = R.id.nav_patch_zip;
            break;
        default:
            throw new IllegalStateException("Invalid initial screen value");
        }

        // Show about screen by default
        mDrawerItemSelected = navId;
    }

    onDrawerItemClicked(mDrawerItemSelected, false);

    refreshOptionalItems();

    // Open drawer on first start
    new Thread() {
        @Override
        public void run() {
            boolean isFirstStart = mPrefs.getBoolean("first_start", true);
            if (isFirstStart) {
                mDrawerLayout.openDrawer(mDrawerView);
                Editor e = mPrefs.edit();
                e.putBoolean("first_start", false);
                e.apply();
            }
        }
    }.start();
}

From source file:com.breadwallet.tools.adapter.ParallaxViewPager.java

/**
 * Sets the background from a resource file.
 *
 * @param resid//w  w w .  jav  a  2s  . c o  m
 */
@Override
public void setBackgroundResource(int resid) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inScaled = true;
    options.inTargetDensity = 100;
    bitmap = BitmapFactory.decodeResource(getResources(), resid, options);
}

From source file:com.netcompss.ffmpeg4android_client.BaseVideo.java

@SuppressWarnings("unused")
private String reporteds(String path) {

    ExifInterface exif = null;/*from  w  w w . j  a v a  2s .c  om*/
    try {
        exif = new ExifInterface(path);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
    Matrix matrix = new Matrix();
    if (orientation == 6) {
        matrix.postRotate(90);
    } else if (orientation == 3) {
        matrix.postRotate(180);
    } else if (orientation == 8) {
        matrix.postRotate(270);
    }

    if (path != null) {

        if (path.contains("http")) {
            try {
                URL url = new URL(path);
                HttpGet httpRequest = null;

                httpRequest = new HttpGet(url.toURI());

                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);

                HttpEntity entity = response.getEntity();
                BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
                InputStream input = bufHttpEntity.getContent();

                Bitmap bitmap = BitmapFactory.decodeStream(input);
                input.close();
                return getPath(bitmap);
            } catch (MalformedURLException e) {
                Log.e("ImageActivity", "bad url", e);
            } catch (Exception e) {
                Log.e("ImageActivity", "io error", e);
            }
        } else {

            Options options = new Options();
            options.inSampleSize = 2;
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeResource(context.getResources(), srcBgId, options);
            options.inJustDecodeBounds = false;
            options.inSampleSize = calculateInSampleSize(options, w, h);
            Bitmap unbgbtmp = BitmapFactory.decodeResource(context.getResources(), srcBgId, options);
            Bitmap unrlbtmp = ScalingUtilities.decodeFile(path, w, h, ScalingLogic.FIT);
            unrlbtmp.recycle();
            Bitmap rlbtmp = null;
            if (unrlbtmp != null) {
                rlbtmp = ScalingUtilities.createScaledBitmap(unrlbtmp, w, h, ScalingLogic.FIT);
            }
            if (unbgbtmp != null && rlbtmp != null) {
                Bitmap bgbtmp = ScalingUtilities.createScaledBitmap(unbgbtmp, w, h, ScalingLogic.FIT);
                Bitmap newscaledBitmap = ProcessingBitmapTwo(bgbtmp, rlbtmp);
                unbgbtmp.recycle();
                return getPath(newscaledBitmap);
            }
        }
    }
    return path;

}

From source file:com.aidigame.hisun.imengstar.huanxin.ChatActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat_huanxin);
    other = (MyUser) getIntent().getSerializableExtra("user");

    rooLayout = (RelativeLayout) findViewById(R.id.root_layout);
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 4;/*  www . j av a 2s  .  c o  m*/
    rooLayout.setBackgroundDrawable(
            new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.blur, options)));

    if (other == null) {
        toChatUsername = getIntent().getStringExtra("userId");
        conversation = EMChatManager.getInstance().getConversation(toChatUsername);
        if (conversation.getMsgCount() > 0) {
            EMMessage lastMessage = conversation.getLastMessage();
            String nick = "";
            String tx = "";
            String userid = "";
            try {
                userid = lastMessage.getStringAttribute("id");
                nick = lastMessage.getStringAttribute("nickname");
                tx = lastMessage.getStringAttribute("tx");
            } catch (EaseMobException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (("" + PetApplication.myUser.userId).equals(userid)) {
                try {
                    nick = lastMessage.getStringAttribute("other_nickname");
                    tx = lastMessage.getStringAttribute("other_tx");
                } catch (EaseMobException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            other = new MyUser();
            other.u_nick = nick;
            other.u_iconUrl = tx;
            other.userId = Integer.parseInt(toChatUsername);
        }
    }

    initView();
    setUpView();

    if (!DemoHXSDKHelper.getInstance().isLogined()) {
        Dialog4Activity.listener = new Dialog4Activity.Dialog3ActivityListener() {

            @Override
            public void onClose() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onButtonTwo() {
                // TODO Auto-generated method stub
                EMChatManager.getInstance().login("" + PetApplication.myUser.userId, PetApplication.myUser.code,
                        new EMCallBack() {

                            @Override
                            public void onSuccess() {
                                // TODO Auto-generated method stub
                                PetApplication.setUserName("" + PetApplication.myUser.userId);
                                PetApplication.setPassword(PetApplication.myUser.code);
                                runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        // TODO Auto-generated method stub
                                        conversation = EMChatManager.getInstance()
                                                .getConversation(toChatUsername);
                                        adapter.conversation = EMChatManager.getInstance()
                                                .getConversation(toChatUsername);
                                        ;
                                        adapter.notifyDataSetChanged();
                                    }
                                });

                            }

                            @Override
                            public void onProgress(int arg0, String arg1) {
                                // TODO Auto-generated method stub

                            }

                            @Override
                            public void onError(int arg0, String arg1) {
                                // TODO Auto-generated method stub

                            }
                        });
            }

            @Override
            public void onButtonOne() {
                // TODO Auto-generated method stub

            }
        };
        Intent intent = new Intent(this, Dialog4Activity.class);
        intent.putExtra("mode", 6);
        startActivity(intent);
    }

}

From source file:Main.java

/**
 * Load bitmap from resources/* w  w w  .j a  va2 s .com*/
 *
 * @param resources  resource
 * @param drawableId resource image id
 * @param imgH       destination image height
 * @param imgW       destination image width
 * @return
 */
public static Bitmap loadHugeBitmapFromDrawable(Resources resources, int drawableId, int imgH, int imgW) {
    Log.d(TAG, "imgH:" + imgH + " imgW:" + imgW);

    BitmapFactory.Options options = new BitmapFactory.Options();

    //preload set inJustDecodeBounds true, this will load bitmap into memory
    options.inJustDecodeBounds = true;
    //options.inPreferredConfig = Bitmap.Config.ARGB_8888;//default is Bitmap.Config.ARGB_8888
    BitmapFactory.decodeResource(resources, drawableId, options);

    //get the image information include: height and width
    int height = options.outHeight;
    int width = options.outWidth;
    String mimeType = options.outMimeType;

    Log.d(TAG, "width:" + width + " height:" + height + " mimeType:" + mimeType);

    //get sample size
    int sampleSize = getScaleInSampleSize(width, height, imgW, imgH);
    options.inSampleSize = sampleSize;
    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    Log.d(TAG, "memory size:" + getBitmapSizeInMemory(width / sampleSize, height / sampleSize));
    Bitmap bitmap = BitmapFactory.decodeResource(resources, drawableId, options);
    Log.d(TAG, "w=" + bitmap.getWidth() + " h=" + bitmap.getHeight() + " bitmap size:"
            + bitmap.getRowBytes() * bitmap.getHeight());
    return bitmap;
}

From source file:ch.ethz.dcg.jukefox.commons.utils.AndroidUtils.java

public static Bitmap getBitmapFromResource(Resources res, int resourceId, int maxSize) {
    Bitmap bitmap = null;//from  ww w  . ja  va2 s .  c o  m
    int dummySize = maxSize * maxSize / 4; // KB
    while (bitmap == null && dummySize <= maxSize * maxSize * 4) {
        try {
            int sampleFactor = getSampleFactor(res, resourceId, maxSize);
            BitmapFactory.Options resample = new BitmapFactory.Options();
            resample.inSampleSize = sampleFactor;
            bitmap = BitmapFactory.decodeResource(res, resourceId, resample);
        } catch (Throwable e) {
            System.gc();
            // Avoid that heap has to be grown for the BitmapFactory,
            // as this would lead to an out of memory error
            int[] dummyArray = new int[dummySize * 1024];
            // Avoid being eliminated by optimization of compiler
            if (dummyArray != null) {
                dummyArray = null;
                System.gc();
            }
            Log.w(TAG, e);
            dummySize *= 2;
        }
    }
    return bitmap;
}

From source file:com.bamobile.fdtks.util.Tools.java

/**
 * Create a new bitmap based on a dummy empty image.
 * This method avoid the expensive Bitmap method Bitmap.createBitmap
 *
 * @param width//  w  ww  .j a va2s  .c  om
 * @param height
 * @return
 */
public static Bitmap createBitmap(int width, int height) {
    Bitmap bmp = BitmapFactory.decodeResource(MainActivity.getInstance().getResources(), R.drawable.empty_image,
            null);
    Bitmap resultBitmap = Bitmap.createScaledBitmap(bmp, width, height, false);
    bmp.recycle();
    bmp = null;
    return resultBitmap;
}

From source file:com.adityarathi.muo.utils.Common.java

/**
 * Resamples a resource image to avoid OOM errors.
 *
 * @param resID Resource ID of the image to be downsampled.
 * @param reqWidth Width of output image.
 * @param reqHeight Height of output image.
 *
 * @return A bitmap of the resampled image.
 *//*from   w  w  w  .j av  a2s  .  c o m*/
public Bitmap decodeSampledBitmapFromResource(int resID, int reqWidth, int reqHeight) {

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;
    options.inPurgeable = true;

    return BitmapFactory.decodeResource(mContext.getResources(), resID, options);
}

From source file:com.atwal.wakeup.battery.util.Utilities.java

public static Bitmap decodeSampledBitmap(Resources resources, int resId, int width, int height) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;//from ww  w  .ja  va 2 s . co  m
    BitmapFactory.decodeResource(resources, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, width, height);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    options.inPreferredConfig = Bitmap.Config.RGB_565;

    return BitmapFactory.decodeResource(resources, resId, options);
}