Example usage for android.graphics Bitmap recycle

List of usage examples for android.graphics Bitmap recycle

Introduction

In this page you can find the example usage for android.graphics Bitmap recycle.

Prototype

public void recycle() 

Source Link

Document

Free the native object associated with this bitmap, and clear the reference to the pixel data.

Usage

From source file:biz.varkon.shelvesom.provider.apparel.ApparelUpdater.java

public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    final ImageUtilities.ExpiringBitmap expiring = new ImageUtilities.ExpiringBitmap();

    while (!mStopped) {
        try {/* ww  w . j a va2 s.c  o  m*/
            final String apparelId = mQueue.take();

            final Long lastCheck = sLastChecks.get(apparelId);
            if (lastCheck != null && (lastCheck + ONE_DAY) >= System.currentTimeMillis()) {
                continue;
            }
            sLastChecks.put(apparelId, System.currentTimeMillis());

            final ApparelStore.Apparel apparel = ApparelManager.findApparel(mResolver, apparelId, null);

            if (apparel == null)
                continue;

            final String imgURL = Preferences.getImageURLForUpdater(apparel);

            if (apparel.getLastModified() == null || imgURL == null) {
                continue;
            }

            if (apparelCoverUpdated(apparel, expiring) && expiring.lastModified != null) {
                ImageUtilities.deleteCachedCover(apparelId);

                final Bitmap bitmap = Preferences.getBitmapForManager(apparel);

                ImportUtilities.addCoverToCache(apparel.getInternalId(), bitmap);

                if (bitmap != null)
                    bitmap.recycle();

                mValues.put(BaseItem.LAST_MODIFIED, expiring.lastModified.getTimeInMillis());
                mArguments[0] = apparelId;
                mResolver.update(ApparelStore.Apparel.CONTENT_URI, mValues, mSelection, mArguments);
            }

            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // Ignore
        }
    }
}

From source file:biz.varkon.shelvesom.provider.software.SoftwareUpdater.java

public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    final ImageUtilities.ExpiringBitmap expiring = new ImageUtilities.ExpiringBitmap();

    while (!mStopped) {
        try {//from  w  w w .j a  v  a2s.c om
            final String softwareId = mQueue.take();

            final Long lastCheck = sLastChecks.get(softwareId);
            if (lastCheck != null && (lastCheck + ONE_DAY) >= System.currentTimeMillis()) {
                continue;
            }
            sLastChecks.put(softwareId, System.currentTimeMillis());

            final SoftwareStore.Software software = SoftwareManager.findSoftware(mResolver, softwareId, null);

            if (software == null)
                continue;

            final String imgURL = Preferences.getImageURLForUpdater(software);

            if (software.getLastModified() == null || imgURL == null) {
                continue;
            }

            if (softwareCoverUpdated(software, expiring) && expiring.lastModified != null) {
                ImageUtilities.deleteCachedCover(softwareId);

                final Bitmap bitmap = Preferences.getBitmapForManager(software);

                ImportUtilities.addCoverToCache(software.getInternalId(), bitmap);

                if (bitmap != null)
                    bitmap.recycle();

                mValues.put(BaseItem.LAST_MODIFIED, expiring.lastModified.getTimeInMillis());
                mArguments[0] = softwareId;
                mResolver.update(SoftwareStore.Software.CONTENT_URI, mValues, mSelection, mArguments);
            }

            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // Ignore
        }
    }
}

From source file:biz.varkon.shelvesom.provider.videogames.VideoGamesUpdater.java

public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    final ImageUtilities.ExpiringBitmap expiring = new ImageUtilities.ExpiringBitmap();

    while (!mStopped) {
        try {/*  ww  w .ja  v  a2s. co  m*/
            final String videogameId = mQueue.take();

            final Long lastCheck = sLastChecks.get(videogameId);
            if (lastCheck != null && (lastCheck + ONE_DAY) >= System.currentTimeMillis()) {
                continue;
            }
            sLastChecks.put(videogameId, System.currentTimeMillis());

            final VideoGamesStore.VideoGame videogame = VideoGamesManager.findVideoGame(mResolver, videogameId,
                    null);

            if (videogame == null)
                continue;

            final String imgURL = Preferences.getImageURLForUpdater(videogame);

            if (videogame.getLastModified() == null || imgURL == null) {
                continue;
            }

            if (videogameCoverUpdated(videogame, expiring) && expiring.lastModified != null) {
                ImageUtilities.deleteCachedCover(videogameId);

                final Bitmap bitmap = Preferences.getBitmapForManager(videogame);

                ImportUtilities.addCoverToCache(videogame.getInternalId(), bitmap);

                if (bitmap != null)
                    bitmap.recycle();

                mValues.put(BaseItem.LAST_MODIFIED, expiring.lastModified.getTimeInMillis());
                mArguments[0] = videogameId;
                mResolver.update(VideoGamesStore.VideoGame.CONTENT_URI, mValues, mSelection, mArguments);
            }

            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // Ignore
        }
    }
}

From source file:biz.varkon.shelvesom.provider.boardgames.BoardGamesUpdater.java

public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    final ImageUtilities.ExpiringBitmap expiring = new ImageUtilities.ExpiringBitmap();

    while (!mStopped) {
        try {//from  www .j  a v  a2s . c  o m
            final String boardgameId = mQueue.take();

            final Long lastCheck = sLastChecks.get(boardgameId);
            if (lastCheck != null && (lastCheck + ONE_DAY) >= System.currentTimeMillis()) {
                continue;
            }
            sLastChecks.put(boardgameId, System.currentTimeMillis());

            final BoardGamesStore.BoardGame boardgame = BoardGamesManager.findBoardGame(mResolver, boardgameId,
                    null);

            if (boardgame == null)
                continue;

            final String imgURL = Preferences.getImageURLForUpdater(boardgame);

            if (boardgame.getLastModified() == null || imgURL == null) {
                continue;
            }

            if (boardgameCoverUpdated(boardgame, expiring) && expiring.lastModified != null) {
                ImageUtilities.deleteCachedCover(boardgameId);

                final Bitmap bitmap = Preferences.getBitmapForManager(boardgame);

                ImportUtilities.addCoverToCache(boardgame.getInternalId(), bitmap);

                if (bitmap != null)
                    bitmap.recycle();

                mValues.put(BaseItem.LAST_MODIFIED, expiring.lastModified.getTimeInMillis());
                mArguments[0] = boardgameId;
                mResolver.update(BoardGamesStore.BoardGame.CONTENT_URI, mValues, mSelection, mArguments);
            }

            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // Ignore
        }
    }
}

From source file:Main.java

public static Bitmap transform(Matrix scaler, Bitmap source, int targetWidth, int targetHeight, boolean scaleUp,
        boolean recycle) {
    int deltaX = source.getWidth() - targetWidth;
    int deltaY = source.getHeight() - targetHeight;
    if (!scaleUp && (deltaX < 0 || deltaY < 0)) {
        /*/*from www  .  j av  a  2s  .  co m*/
         * In this case the bitmap is smaller, at least in one dimension,
         * than the target.  Transform it by placing as much of the image
         * as possible into the target and leaving the top/bottom or
         * left/right (or both) black.
         */
        Bitmap b2 = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b2);

        int deltaXHalf = Math.max(0, deltaX / 2);
        int deltaYHalf = Math.max(0, deltaY / 2);
        Rect src = new Rect(deltaXHalf, deltaYHalf, deltaXHalf + Math.min(targetWidth, source.getWidth()),
                deltaYHalf + Math.min(targetHeight, source.getHeight()));
        int dstX = (targetWidth - src.width()) / 2;
        int dstY = (targetHeight - src.height()) / 2;
        Rect dst = new Rect(dstX, dstY, targetWidth - dstX, targetHeight - dstY);
        c.drawBitmap(source, src, dst, null);
        if (recycle) {
            source.recycle();
        }
        return b2;
    }
    float bitmapWidthF = source.getWidth();
    float bitmapHeightF = source.getHeight();

    float bitmapAspect = bitmapWidthF / bitmapHeightF;
    float viewAspect = (float) targetWidth / targetHeight;

    if (bitmapAspect > viewAspect) {
        float scale = targetHeight / bitmapHeightF;
        if (scale < .9F || scale > 1F) {
            scaler.setScale(scale, scale);
        } else {
            scaler = null;
        }
    } else {
        float scale = targetWidth / bitmapWidthF;
        if (scale < .9F || scale > 1F) {
            scaler.setScale(scale, scale);
        } else {
            scaler = null;
        }
    }

    Bitmap b1;
    if (scaler != null) {
        // this is used for minithumb and crop, so we want to filter here.
        b1 = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), scaler, true);
    } else {
        b1 = source;
    }

    if (recycle && b1 != source) {
        source.recycle();
    }

    int dx1 = Math.max(0, b1.getWidth() - targetWidth);
    int dy1 = Math.max(0, b1.getHeight() - targetHeight);

    Bitmap b2 = Bitmap.createBitmap(b1, dx1 / 2, dy1 / 2, targetWidth, targetHeight);

    if (b2 != b1) {
        if (recycle || b1 != source) {
            b1.recycle();
        }
    }

    return b2;
}

From source file:Main.java

/**
 * /*  www  .ja v a 2s  .c  o m*/
 * @param filePath
 * @param targetWidth
 * @param targetHeight
 * @param recycle
 * @return
 */
public static Bitmap resizeAndCropCenter(String filePath, int targetWidth, int targetHeight, boolean recycle) {
    //get sampleBitmap
    Options opts = new Options();
    opts.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, opts);

    int scaleWidth = opts.outWidth / targetWidth;
    int scaleHeight = opts.outHeight / targetHeight;
    int scale = scaleWidth < scaleHeight ? scaleWidth : scaleHeight;
    if (scale < 1) {
        scale = 1;
    }
    opts.inJustDecodeBounds = false;
    opts.inSampleSize = scale;
    Bitmap sampleBitmap = BitmapFactory.decodeFile(filePath, opts);

    if (opts.outWidth == -1 || opts.outHeight == -1) {
        throw new IllegalArgumentException();
    }
    //get scalebitmap
    float fScaleWidth = targetWidth / ((float) opts.outWidth);
    float fScaleHeight = targetHeight / ((float) opts.outHeight);
    float fScale = fScaleWidth > fScaleHeight ? fScaleWidth : fScaleHeight;
    if (fScale > 1)
        fScale = 1;
    Matrix matrix = new Matrix();
    matrix.postScale(fScale, fScale);
    Bitmap scaleBitmap = Bitmap.createBitmap(sampleBitmap, 0, 0, opts.outWidth, opts.outHeight, matrix, true);

    //get targetBitmap
    int bitmapX = (scaleBitmap.getWidth() - targetWidth) / 2;
    bitmapX = bitmapX > 0 ? bitmapX : 0;
    int bitmapY = (scaleBitmap.getHeight() - targetHeight) / 2;
    bitmapY = bitmapY > 0 ? bitmapY : 0;
    targetWidth = targetWidth < (scaleBitmap.getWidth()) ? targetWidth : (scaleBitmap.getWidth());
    targetHeight = targetHeight < (scaleBitmap.getHeight()) ? targetHeight : (scaleBitmap.getHeight());
    Bitmap targetBitmap = Bitmap.createBitmap(scaleBitmap, bitmapX, bitmapY, targetWidth, targetHeight);

    if (recycle)
        sampleBitmap.recycle();
    return targetBitmap;
}

From source file:Main.java

/**
 * Loads a texture from a resource ID, returning the OpenGL ID for that
 * texture. Returns 0 if the load failed.
 * // ww w.  jav  a  2 s  .  c om
 * @param context
 * @param resourceId
 * @return
 */
public static int loadTexture(Context context, int resourceId) {
    final int[] textureObjectIds = new int[1];
    glGenTextures(1, textureObjectIds, 0);

    if (textureObjectIds[0] == 0) {
        Log.w(TAG, "Could not generate a new OpenGL texture object.");
        return 0;
    }

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inScaled = false;

    // Read in the resource
    final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId, options);

    if (bitmap == null) {
        Log.w(TAG, "Resource ID " + resourceId + " could not be decoded.");
        glDeleteTextures(1, textureObjectIds, 0);
        return 0;
    }

    // Bind to the texture in OpenGL
    glBindTexture(GL_TEXTURE_2D, textureObjectIds[0]);

    // Set filtering: a default must be set, or the texture will be
    // black.
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // Load the bitmap into the bound texture.
    texImage2D(GL_TEXTURE_2D, 0, bitmap, 0);

    // Note: Following code may cause an error to be reported in the
    // ADB log as follows: E/IMGSRV(20095): :0: HardwareMipGen:
    // Failed to generate texture mipmap levels (error=3)
    // No OpenGL error will be encountered (glGetError() will return
    // 0). If this happens, just squash the source image to be
    // square. It will look the same because of texture coordinates,
    // and mipmap generation will work.

    glGenerateMipmap(GL_TEXTURE_2D);

    // Recycle the bitmap, since its data has been loaded into
    // OpenGL.
    bitmap.recycle();

    // Unbind from the texture.
    glBindTexture(GL_TEXTURE_2D, 0);

    return textureObjectIds[0];
}

From source file:com.concentricsky.android.khanacademy.util.ThumbnailManager.java

private LruCache<Thumbnail, Bitmap> prepareCache() {
    // Total available heap size. This changes based on manifest android:largeHeap="true". (Fire HD, transformer both go from 48MB to 256MB)
    Runtime rt = Runtime.getRuntime();
    long maxMemory = rt.maxMemory();
    Log.v(LOG_TAG, "maxMemory:" + Long.toString(maxMemory));

    // Want to use at most about 1/2 of available memory for thumbs.
    // In SAT Math category (116 videos), with a heap size of 48MB, this setting
    // allows 109 thumbs to be cached resulting in total heap usage around 34MB.
    long usableMemory = maxMemory / 2;

    return new LruCache<Thumbnail, Bitmap>((int) usableMemory) {
        @Override//from w  w w  . j  a  v a  2s  .c  o m
        protected int sizeOf(Thumbnail key, Bitmap value) {
            return value.getByteCount();
        }

        @Override
        protected void entryRemoved(boolean evicted, Thumbnail key, Bitmap oldValue, Bitmap newValue) {
            if (oldValue != newValue) {
                oldValue.recycle();
            }
        }
    };

}

From source file:Main.java

public static Bitmap convertToMutable(Bitmap srcBitmap, String cacheDirPath, String tempFileName) {
    try {//from ww w .j av a  2 s.  com
        // this is the file going to use temporally to save the bytes.
        // This file will not be a image, it will store the raw image data.
        int index = tempFileName.lastIndexOf(".");
        if (index != -1)
            tempFileName = tempFileName.substring(0, index);
        File file = new File(cacheDirPath + File.separator + tempFileName + ".tmp");

        // Open an RandomAccessFile
        // Make sure you have added uses-permission
        // android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        // into AndroidManifest.xml file
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");

        // get the width and height of the source bitmap.
        int width = srcBitmap.getWidth();
        int height = srcBitmap.getHeight();
        Config type = srcBitmap.getConfig();

        // Copy the byte to the file
        // Assume source bitmap loaded using options.inPreferredConfig =
        // Config.ARGB_8888;
        FileChannel channel = randomAccessFile.getChannel();
        MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, srcBitmap.getRowBytes() * height);
        srcBitmap.copyPixelsToBuffer(map);
        // recycle the source bitmap, this will be no longer used.
        srcBitmap.recycle();
        System.gc();// try to force the bytes from the imgIn to be released

        // Create a new bitmap to load the bitmap again. Probably the memory
        // will be available.
        srcBitmap = Bitmap.createBitmap(width, height, type);
        map.position(0);
        // load it back from temporary
        srcBitmap.copyPixelsFromBuffer(map);
        // close the temporary file and channel , then delete that also
        channel.close();
        randomAccessFile.close();

        // delete the temp file
        file.delete();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return srcBitmap;
}

From source file:com.liato.bankdroid.banking.banks.Nordea.Nordea.java

@Override
public Urllib login() throws LoginException, BankException {
    try {/*from   w  w  w. j  a v a  2 s .  c o  m*/
        LoginPackage lp = preLogin();
        String response = urlopen.open(lp.getLoginTarget(), lp.getPostData());
        if (response.contains("felaktiga uppgifter")) {
            throw new LoginException(res.getText(R.string.invalid_username_password).toString());
        } else if (response.contains("nloggningar med ditt personnummer idag")) {
            Matcher matcher = reCSRF.matcher(response);
            if (!matcher.find()) {
                throw new BankException(res.getText(R.string.unable_to_find).toString() + " CSRF token.");
            }
            String csrftoken = matcher.group(1);
            Iterator<NameValuePair> it = lp.getPostData().iterator();
            while (it.hasNext()) {
                NameValuePair nv = it.next();
                if (nv.getName().equals("_csrf_token")) {
                    it.remove();
                    break;
                }
            }
            lp.getPostData().add(new BasicNameValuePair("_csrf_token", csrftoken));
            //Too many logins, we need to solve a captcha.
            Bitmap bm = BitmapFactory.decodeStream(
                    urlopen.openStream("https://mobil.nordea.se/banking-nordea/nordea-c3/captcha.png"));
            String captcha = CaptchaBreaker.iMustBreakYou(bm);
            bm.recycle();
            bm = null;
            lp.getPostData().add(new BasicNameValuePair("captcha", captcha));
            response = urlopen.open(lp.getLoginTarget(), lp.getPostData());
            if (response.contains("felaktiga uppgifter")) {
                throw new LoginException(res.getText(R.string.invalid_username_password).toString());
            }
        }

    } catch (ClientProtocolException e) {
        throw new BankException(e.getMessage());
    } catch (IOException e) {
        throw new BankException(e.getMessage());
    }
    return urlopen;
}