Code example for Bitmap

Methods: createScaledBitmapgetHeightgetWidthrecycle

0
     * @param height   preferred height of the new image 
     * @param upsample if true smaller images than the preferred size are increased, if false the origin bitmap is returned 
     * @return new bitmap if size has changed, otherwise original bitmap. 
     */ 
    public Bitmap scaleBitmap(Bitmap b, int width, int height, boolean upsampling) {
        int imageHeight = b.getHeight();
        int imageWidth = b.getWidth();
        if (!upsampling && imageHeight <= height && imageWidth <= width) {
            return b;
        } 
        int finalWidth = width;
        int finalHeight = height;
        if (imageHeight > imageWidth) {
            float factor = ((float) height) / ((float) imageHeight);
            finalHeight = new Float(imageHeight * factor).intValue();
            finalWidth = new Float(imageWidth * factor).intValue();
        } else { 
            float factor = ((float) width) / ((float) imageWidth);
            finalHeight = new Float(imageHeight * factor).intValue();
            finalWidth = new Float(imageWidth * factor).intValue();
        } 
        Bitmap scaled = null;
        try { 
            scaled = Bitmap.createScaledBitmap(b, finalWidth, finalHeight, true);
        } catch (final Throwable e) {
            // calling gc does not help as is called anyway 
            // http://code.google.com/p/android/issues/detail?id=8488#c80 
            // System.gc(); 
        } 
        // recycle b only if createScaledBitmap returned a new instance. 
        if (scaled != b) {
            recycle(b);
        } 
        return scaled;
    } 
 
    /** 
     * Convenience method to decode an input stream as a bitmap using BitmapFactory.decodeStream without any parameter options. 
     * <p/> 
     * If decoding fails the input stream is closed. 
     * 
     * @param is input stream of image data 
     * @return bitmap created from the given input stream. 
     */ 
    public Bitmap decodeInputStream(InputStream is) {
        Bitmap bitmap = null;
        try { 
            bitmap = BitmapFactory.decodeStream(is, null, null);
        } catch (final Throwable e) {
            // calling gc does not help as is called anyway 
            // http://code.google.com/p/android/issues/detail?id=8488#c80 
            // System.gc(); 
        } finally { 
            closeSilently(is);
        } 
        return bitmap;
    } 
 
    private void recycle(Bitmap scaled) {
        try { 
            scaled.recycle();
        } catch (Exception e) {
            // 
        } 
    }