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:com.netcompss.ffmpeg4android_client.BaseWizard.java

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

    ExifInterface exif = null;// w w  w .ja  v a 2s  .  c  o m
    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(getApplicationContext().getResources(), srcBgId, options);
            options.inJustDecodeBounds = false;
            options.inSampleSize = calculateInSampleSize(options, w, h);
            Bitmap unbgbtmp = BitmapFactory.decodeResource(getApplicationContext().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.example.psumaps.MapView.java

public static Bitmap convertToMutable(Bitmap imgIn) {
    try {//  ww w .j  a va 2s  .  co  m
        // 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.
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "temp.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 = imgIn.getWidth();
        int height = imgIn.getHeight();
        Bitmap.Config type = imgIn.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(FileChannel.MapMode.READ_WRITE, 0, imgIn.getRowBytes() * height);
        imgIn.copyPixelsToBuffer(map);
        // recycle the source bitmap, this will be no longer used.
        imgIn.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.
        imgIn = Bitmap.createBitmap(width, height, type);
        map.position(0);
        // load it back from temporary
        imgIn.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 imgIn;
}

From source file:com.ryan.ryanreader.reddit.prepared.RedditPreparedPost.java

private void downloadThumbnail(final Context context, final int widthPixels, final CacheManager cm,
        final int listId, final boolean highRes) {

    final String uriStr = highRes ? imageUrl : thumbnailUrl;
    final URI uri = General.uriFromString(uriStr);

    final int priority = highRes ? Constants.Priority.IMAGE_PRECACHE : Constants.Priority.THUMBNAIL;
    final int fileType = highRes ? Constants.FileType.IMAGE : Constants.FileType.THUMBNAIL;

    final RedditAccount anon = RedditAccountManager.getAnon();

    cm.makeRequest(new CacheRequest(uri, anon, null, priority, listId, CacheRequest.DownloadType.IF_NECESSARY,
            fileType, false, false, false, context) {

        @Override/*w  w w  .  j a  v  a2s .c o  m*/
        protected void onDownloadNecessary() {
        }

        @Override
        protected void onDownloadStarted() {
        }

        @Override
        protected void onCallbackException(final Throwable t) {
            // TODO handle -- internal error
            throw new RuntimeException(t);
        }

        @Override
        protected void onFailure(final RequestFailureType type, final Throwable t, final StatusLine status,
                final String readableMessage) {
        }

        @Override
        protected void onProgress(final long bytesRead, final long totalBytes) {
        }

        @Override
        protected void onSuccess(final CacheManager.ReadableCacheFile cacheFile, final long timestamp,
                final UUID session, final boolean fromCache, final String mimetype) {

            // The lock avoids using too much memory
            synchronized (singleImageDecodeLock) {

                if (gotHighResThumb && !highRes)
                    return;

                try {
                    final Bitmap data = BitmapFactory.decodeStream(cacheFile.getInputStream());
                    if (data == null)
                        return;
                    thumbnailCache = ThumbnailScaler.scale(data, widthPixels);
                    if (thumbnailCache != data)
                        data.recycle();

                    if (highRes)
                        gotHighResThumb = true;

                    if (thumbnailCallback != null)
                        thumbnailCallback.betterThumbnailAvailable(thumbnailCache, usageId);

                } catch (OutOfMemoryError e) {
                    // TODO handle this better - disable caching of images
                    Log.e("RedditPreparedPost", "Out of memory trying to download image");
                    e.printStackTrace();
                    return;

                } catch (Throwable t) {
                    // Just ignore it.
                }
            }
        }
    });
}

From source file:com.spoiledmilk.ibikecph.util.Util.java

public static Bitmap bmpDecodeFile(File f, int width_limit, int height_limit, long max_size,
        boolean max_dimensions) {
    if (f == null) {
        return null;
    }/*  ww w  .ja  v a 2 s  . co  m*/

    LOG.d("bmpDecodeFile(" + f.getAbsolutePath() + "," + width_limit + "," + height_limit + "," + max_size + ","
            + max_dimensions + ")");

    Bitmap bmp = null;
    boolean shouldReturn = false;

    FileInputStream fin = null;
    int orientation = ExifInterface.ORIENTATION_NORMAL;
    try {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        fin = new FileInputStream(f);
        BitmapFactory.decodeStream(fin, null, o);
        try {
            fin.close();
            fin = null;
        } catch (IOException e) {
        }

        // Find the correct scale value. It should be the power of 2.
        int scale = 1;
        if (width_limit != -1 && height_limit != -1) {
            if (max_dimensions) {
                while (o.outWidth / scale > width_limit || o.outHeight / scale > height_limit)
                    scale *= 2;
            } else {
                while (o.outWidth / scale / 2 >= width_limit && o.outHeight / scale / 2 >= height_limit)
                    scale *= 2;
            }
        } else if (max_size != -1)
            while ((o.outWidth * o.outHeight) / (scale * scale) > max_size)
                scale *= 2;

        // Decode with inSampleSize
        o = null;
        if (scale > 1) {
            o = new BitmapFactory.Options();
            o.inSampleSize = scale;
        }
        fin = new FileInputStream(f);
        try {
            bmp = BitmapFactory.decodeStream(fin, null, o);
        } catch (OutOfMemoryError e) {
            // Try to recover from out of memory error - but keep in mind
            // that behavior after this error is
            // undefined,
            // for example more out of memory errors might appear in catch
            // block.
            if (bmp != null)
                bmp.recycle();
            bmp = null;
            System.gc();
            LOG.e("Util.bmpDecodeFile() OutOfMemoryError in decodeStream()! Trying to recover...");
        }

        if (bmp != null) {
            LOG.d("resulting bitmap width : " + bmp.getWidth() + " height : " + bmp.getHeight() + " size : "
                    + (bmp.getRowBytes() * bmp.getHeight()));

            ExifInterface exif = new ExifInterface(f.getPath());
            orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        }
    } catch (FileNotFoundException e) {
        shouldReturn = true;
    } catch (IOException e) {
        shouldReturn = true; // bitmap is still valid here, just can't be
        // rotated
    } finally {
        if (fin != null)
            try {
                fin.close();
            } catch (IOException e) {
            }
    }

    if (shouldReturn || bmp == null)
        return bmp;

    float rotate = 0;
    switch (orientation) {
    case ExifInterface.ORIENTATION_ROTATE_90:
        rotate = 90;
        break;
    case ExifInterface.ORIENTATION_ROTATE_180:
        rotate = 180;
        break;
    case ExifInterface.ORIENTATION_ROTATE_270:
        rotate = 270;
        break;
    }
    if (rotate > 0) {
        Matrix matrix = new Matrix();
        matrix.postRotate(rotate);
        Bitmap bmpRot = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
        matrix = null;
        bmp.recycle();
        bmp = null;
        // System.gc();
        return bmpRot;
    }

    return bmp;
}

From source file:com.github.gorbin.asne.vk.VkSocialNetwork.java

/**
 * Post photo to social network/*ww  w.j a  va2 s  .  c  o m*/
 * @param photo photo that should be shared
 * @param message message that should be shared with photo
 * @param onPostingCompleteListener listener for posting request
 */
@Override
public void requestPostPhoto(File photo, final String message,
        OnPostingCompleteListener onPostingCompleteListener) {
    super.requestPostPhoto(photo, message, onPostingCompleteListener);
    final Bitmap vkPhoto = getPhoto(photo);
    VKRequest request = VKApi.uploadWallPhotoRequest(new VKUploadImage(vkPhoto, VKImageParameters.pngImage()),
            0, Integer.parseInt(mUserId));
    request.executeWithListener(new VKRequest.VKRequestListener() {
        @Override
        public void onComplete(VKResponse response) {
            VKApiPhoto photoModel = ((VKPhotoArray) response.parsedModel).get(0);
            makePost(new VKAttachments(photoModel), message, REQUEST_POST_PHOTO);
            vkPhoto.recycle();
        }

        @Override
        public void onError(VKError error) {
            mLocalListeners.get(REQUEST_POST_PHOTO).onError(getID(), REQUEST_POST_PHOTO, error.toString(),
                    null);
        }
    });
}

From source file:com.aimfire.gallery.cardboard.PhotoActivity.java

/**
 * load full width sbs images into textures. 
 * @param index/*www .j  a  v  a  2s . c o m*/
 */
private int[] loadSbsImage(int index) {
    String sbsPath = mAssetList.get(index);

    /*
     * tried BitmapRegionDecoder but it returns null on the right bitmap
     * below. seems like a bug in android, c.f. "https://code.google.com
     * /p/android/issues/detail?id=80316", that manifest when the rect
     * is on the boundary. so, abandoned
     */
    //      BitmapRegionDecoder decoder = null;
    //      try {
    //         decoder = BitmapRegionDecoder.newInstance(imgPath, false);
    //      } catch (IOException e) {
    //         e.printStackTrace();
    //      }
    //        
    //      BitmapFactory.Options options = new BitmapFactory.Options();
    //        int width = decoder.getWidth()/2;
    //        int height = decoder.getHeight();

    //      mBmpL = decoder.decodeRegion(
    //            new Rect(0, 0, width, height), options);
    //      mBmpR = decoder.decodeRegion(
    //            new Rect(width, 0, width, height), options);
    //      decoder.recycle();

    int width = -1;
    int height = -1;

    try {
        Bitmap sbsBitmap = BitmapFactory.decodeFile(sbsPath);
        if (!mAssetColor) {
            sbsBitmap = toGrayscale(sbsBitmap);
        }
        width = sbsBitmap.getWidth() / 2;
        height = sbsBitmap.getHeight();

        mBmpL = Bitmap.createBitmap(sbsBitmap, 0, 0, width, height);
        mBmpR = Bitmap.createBitmap(sbsBitmap, width, 0, width, height);

        sbsBitmap.recycle();
    } catch (Exception e) {
        e.printStackTrace();
    }

    /*
     * left/right picture dimensions should be identical
     */
    return (new int[] { width, height });
}

From source file:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java

/*******************************
 * //from  w w  w . ja  v  a2s  . c  om
 * checkAlbumArtEmbeddedSize
 * 
 *******************************/
public String checkAlbumArtEmbeddedSize(String albumCoverPath) {

    /* check if the embedded mp3 is valid (or big enough)*/
    if (albumCoverPath != null) {
        Log.i("DBG", albumCoverPath);
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        Bitmap bmTmp = BitmapFactory.decodeFile(albumCoverPath, opts);
        if (opts == null || opts.outHeight < 320 || opts.outWidth < 320)
            albumCoverPath = null;
        if (bmTmp != null)
            bmTmp.recycle();
    }

    return albumCoverPath;

}

From source file:com.bilibili.boxing.utils.CameraPickerHelper.java

private boolean rotateSourceFile(File file) throws IOException {
    if (file == null || !file.exists()) {
        return false;
    }/*from  w w  w . j a  va  2 s  .  c  o  m*/
    FileOutputStream outputStream = null;
    Bitmap bitmap = null;
    Bitmap outBitmap = null;
    try {
        int degree = BoxingExifHelper.getRotateDegree(file.getAbsolutePath());
        Matrix matrix = new Matrix();
        if (degree != 0) {
            matrix.postRotate(degree);
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
        outBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
        outputStream = new FileOutputStream(file);
        outBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        outputStream.flush();
        return true;
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                BoxingLog.d("IOException when output stream closing!");
            }
        }
        if (bitmap != null) {
            bitmap.recycle();
        }
        if (outBitmap != null) {
            outBitmap.recycle();
        }
    }
}

From source file:Main.java

public static Bitmap rotateBitmap(String path, int orientation, int screenWidth, int screenHeight) {
    Bitmap bitmap = null;
    final int maxWidth = screenWidth / 2;
    final int maxHeight = screenHeight / 2;
    try {//from   www . j  a va 2 s. c om
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        int sourceWidth, sourceHeight;
        if (orientation == 90 || orientation == 270) {
            sourceWidth = options.outHeight;
            sourceHeight = options.outWidth;
        } else {
            sourceWidth = options.outWidth;
            sourceHeight = options.outHeight;
        }
        boolean compress = false;
        if (sourceWidth > maxWidth || sourceHeight > maxHeight) {
            float widthRatio = (float) sourceWidth / (float) maxWidth;
            float heightRatio = (float) sourceHeight / (float) maxHeight;

            options.inJustDecodeBounds = false;
            if (new File(path).length() > 512000) {
                float maxRatio = Math.max(widthRatio, heightRatio);
                options.inSampleSize = (int) maxRatio;
                compress = true;
            }
            bitmap = BitmapFactory.decodeFile(path, options);
        } else {
            bitmap = BitmapFactory.decodeFile(path);
        }
        if (orientation > 0) {
            Matrix matrix = new Matrix();
            //matrix.postScale(sourceWidth, sourceHeight);
            matrix.postRotate(orientation);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        }
        sourceWidth = bitmap.getWidth();
        sourceHeight = bitmap.getHeight();
        if ((sourceWidth > maxWidth || sourceHeight > maxHeight) && compress) {
            float widthRatio = (float) sourceWidth / (float) maxWidth;
            float heightRatio = (float) sourceHeight / (float) maxHeight;
            float maxRatio = Math.max(widthRatio, heightRatio);
            sourceWidth = (int) ((float) sourceWidth / maxRatio);
            sourceHeight = (int) ((float) sourceHeight / maxRatio);
            Bitmap bm = Bitmap.createScaledBitmap(bitmap, sourceWidth, sourceHeight, true);
            bitmap.recycle();
            return bm;
        }
    } catch (Exception e) {
    }
    return bitmap;
}

From source file:org.lol.reddit.reddit.prepared.RedditPreparedPost.java

private void downloadThumbnail(final Context context, final int widthPixels, final CacheManager cm,
        final int listId, final boolean highRes) {

    final String uriStr = highRes ? imageUrl : thumbnailUrl;
    final URI uri = General.uriFromString(uriStr);

    final int priority = highRes ? Constants.Priority.IMAGE_PRECACHE : Constants.Priority.THUMBNAIL;
    final int fileType = highRes ? Constants.FileType.IMAGE : Constants.FileType.THUMBNAIL;

    final RedditAccount anon = RedditAccountManager.getAnon();

    cm.makeRequest(new CacheRequest(uri, anon, null, priority, listId, CacheRequest.DownloadType.IF_NECESSARY,
            fileType, false, false, false, context) {

        @Override/*from ww  w  .j  a va 2s  .  c o m*/
        protected void onDownloadNecessary() {
        }

        @Override
        protected void onDownloadStarted() {
        }

        @Override
        protected void onCallbackException(final Throwable t) {
            // TODO handle -- internal error
            throw new RuntimeException(t);
        }

        @Override
        protected void onFailure(final RequestFailureType type, final Throwable t, final StatusLine status,
                final String readableMessage) {
        }

        @Override
        protected void onProgress(final long bytesRead, final long totalBytes) {
        }

        @Override
        protected void onSuccess(final CacheManager.ReadableCacheFile cacheFile, final long timestamp,
                final UUID session, final boolean fromCache, final String mimetype) {

            if (gotHighResThumb && !highRes)
                return;
            try {

                synchronized (singleImageDecodeLock) {

                    BitmapFactory.Options justDecodeBounds = new BitmapFactory.Options();
                    justDecodeBounds.inJustDecodeBounds = true;
                    BitmapFactory.decodeStream(cacheFile.getInputStream(), null, justDecodeBounds);
                    final int width = justDecodeBounds.outWidth;
                    final int height = justDecodeBounds.outHeight;

                    int factor = 1;

                    while (width / (factor + 1) > widthPixels && height / (factor + 1) > widthPixels)
                        factor *= 2;

                    BitmapFactory.Options scaledOptions = new BitmapFactory.Options();
                    scaledOptions.inSampleSize = factor;

                    final Bitmap data = BitmapFactory.decodeStream(cacheFile.getInputStream(), null,
                            scaledOptions);

                    if (data == null)
                        return;
                    thumbnailCache = ThumbnailScaler.scale(data, widthPixels);
                    if (thumbnailCache != data)
                        data.recycle();
                }

                if (highRes)
                    gotHighResThumb = true;

                if (thumbnailCallback != null)
                    thumbnailCallback.betterThumbnailAvailable(thumbnailCache, usageId);

            } catch (OutOfMemoryError e) {
                // TODO handle this better - disable caching of images
                Log.e("RedditPreparedPost", "Out of memory trying to download image");
                e.printStackTrace();
            } catch (Throwable t) {
                // Just ignore it.
            }
        }
    });
}